Jump to content
Sign in to follow this  
Grateful Grant

Contact form captcha not working. Anything obvious?

Recommended Posts

I recently noticed that my Contact form is not working.

It always says that the captcha code doesn't match.

 

Any ideas please? I assume it shouldn't have stopped working by itself?

Maybe you can see something obvious, please?

 

Thanks for any advice.

 

Here's the php:

<?php 
$your_email ='grant@grantbarker.com';// <<=== update to your email address

session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';

if(isset($_POST['submit']))
{
	
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	//$visitor_link = $_POST['link'];
	///------------Do Validations-------------
	if(empty($name)||empty($visitor_email))
	{
		$errors .= "\n Sorry, Your Name and Your Email are required fields. ";	
	}
	if(IsInjected($visitor_email))
	{
		$errors .= "\n Bad email value!";
	}
	if(empty($_SESSION['6_letters_code'] ) ||
	  strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
	//Note: the captcha code is compared case insensitively.
	//if you want case sensitive match, update the check above to
	// strcmp()
		$errors .= "\n It looks like the captcha code does not match.";
	}
	
	if(empty($errors))
	{
		//send the email
		$to = $your_email;
		$subject="GrantBarker.com Enquiry";
		$from = $your_email;
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		
		$body = "A user  $name submitted the contact form:\n".
		"Name: $name\n".
		"Email: $visitor_email \n".
		//"Link: $visitor_link \n".
		"Message: \n ".
		"$user_message\n".
		"IP: $ip\n";	
		
		$headers = "From: $from \r\n";
		$headers .= "Reply-To: $visitor_email \r\n";
		
		mail($to, $subject, $body,$headers);
		
		header('Location: thankyou.php');
	}
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?><div id='contact_form_errorloc' class='err'></div>
        <form method="post" name="contact_form" id="contact-form" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" >
			<div>
				<label for="name">
					<span>Your Name (required)</span></label>
					<input type="text" name="name" autofocus value="<?php echo htmlentities($name) ?>">
				
			</div>
			<div>
				<label for="email">
					<span>Your Email (required)</span></label>
					<input type="email" name="email" value="<?php echo htmlentities($visitor_email) ?>" >
				
			</div>
            <div>
				<label for="message">
					<span>Your Message</span></label>
					<textarea name="message" ><?php echo htmlentities($user_message) ?></textarea>
				
			</div><div><p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>

Share this post


Link to post
Share on other sites

Hmm I can't see where you set the $_SESSION['6_letters_code'], somewhere it should store the rand to the $_SESSION['6_letters_code'] - is there any more to this?

 

Edit: Also where the image is have you clipped of the next bit of code? Image isn't closed, no closing </form> either.

Edited by BrowserBugs

Share this post


Link to post
Share on other sites

Thanks BrowserBugs.

 

It links to captcha_code_file.php:

<?php 
/*
*
* this code is based on captcha code by Simon Jarvis 
* http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*
* This program is free software; you can redistribute it and/or 
* modify it under the terms of the GNU General Public License 
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, 
* but WITHOUT ANY WARRANTY; without even the implied warranty of 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
* GNU General Public License for more details: 
* http://www.gnu.org/licenses/gpl.html
*/

session_start();
//Settings: You can customize the captcha here
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 0;
$random_lines = 20;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";

$code = '';


$i = 0;
while ($i < $characters_on_image) { 
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}


$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);


/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'], 
		$arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'], 
		$arr_noice_color['green'], $arr_noice_color['blue']);


/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}


/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}


/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code); 
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);


/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
$_SESSION['6_letters_code'] = $code;

function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}
?>

Below is the whole of the first post Contact page including the html and php:

(Just to make sure I haven't clipped anything off.)

 

Sorry for the huge post! The last thing I changed a few months ago was to add my ugly mug photo. (I should have tested it at the time and probably did). I noticed it wasn't working 2 days ago when I was showing it as an example to my boss who was showing her new website for her business. It was embarrassing that mine wasn't working either.

 

At first it only worked in Firefox (as opposed to Edge, Opera and Chrome) when I checked today and then it stopped working, possibly related to an FF update?. My browser caches should have been pretty empty, especially for Firefox, as I have recently reinstalled Windows.

I don't know so much about php technology. My search function works, and my server is now from today defaulting to use php 7.1. I changed it today from the original default of php5.6 but I guess that might not make a difference, and this stopped working before changing any php server defaults.

 

Thank you for any further advice and help.

<?php 
$your_email ='grant@grantbarker.com';// <<=== update to your email address

session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';

if(isset($_POST['submit']))
{
	
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	//$visitor_link = $_POST['link'];
	///------------Do Validations-------------
	if(empty($name)||empty($visitor_email))
	{
		$errors .= "\n Sorry, Your Name and Your Email are required fields. ";	
	}
	if(IsInjected($visitor_email))
	{
		$errors .= "\n Bad email value!";
	}
	if(empty($_SESSION['6_letters_code'] ) ||
	  strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
	//Note: the captcha code is compared case insensitively.
	//if you want case sensitive match, update the check above to
	// strcmp()
		$errors .= "\n It looks like the captcha code does not match.";
	}
	
	if(empty($errors))
	{
		//send the email
		$to = $your_email;
		$subject="GrantBarker.com Enquiry";
		$from = $your_email;
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		
		$body = "A user  $name submitted the contact form:\n".
		"Name: $name\n".
		"Email: $visitor_email \n".
		//"Link: $visitor_link \n".
		"Message: \n ".
		"$user_message\n".
		"IP: $ip\n";	
		
		$headers = "From: $from \r\n";
		$headers .= "Reply-To: $visitor_email \r\n";
		
		mail($to, $subject, $body,$headers);
		
		header('Location: thankyou.php');
	}
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<!doctype html>
<html lang="en" itemscope itemtype="http://schema.org/ContactPage">
<head>


<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width">
<link href="https://fonts.googleapis.com/css?family=Sniglet" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.27/webfont.js"></script>
<script>
  WebFont.load({
    google: {
      families: ['Sniglet']
    }
  });
</script>

<title>Contact Grant Barker</title>

<script src="p7ehc/p7EHCscripts.js"></script>
<link href="p7dmm/m.css" rel="stylesheet" type="text/css" media="all">
<script src="p7dmm/p7DMMscripts.js"></script>
<link href="aa/love.css" rel="stylesheet" type="text/css">
<script src="jquery.js"></script>


<link href="aa/contact.css" rel="stylesheet">


<style>h4{font-size:1.4em;margin-top:10px;}</style>
<!--[if lte IE 7]>
<style>
body {min-width: 1020px;}
.columns-wrapper, .menu-top-wrapper, .p7dmm-sub-wrapper {width: 980px;}
</style>
<![endif]-->

</head>

<body>
 <svg style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>


</defs>
</svg>
  <div class="masthead"><p class="site-description">Blog, Windows, News you can use & ROMs</p><h4 class="site-title"><a href="https://www.grantbarker.com" title="Grant Barker - Home">GrantBarker<em class="gbcom">.com</em></a></h4>
  <a href="https://www.grantbarker.com" title="Grant Barker - Home"><img src="images/grantbarker-com.png"  alt="Grant Barker - Home" width="68" height="84" class="masthead gbimg" id="top"></a><div class="social-container">
    </div>
  <div class="toptab"><a href="about/grantbarker-com" title="About GrantBarker.com">About</a> | <a href="contact.php" title="Contact Grant Barker">Contact</a><br>
</div>
</div>
   
<div class="content-wrapper">
  <div class="columns-wrapper">
    <div class="main-content">
      <div class="content p7ehc-1">
        <h1>Contact Grant</h1>
        <p>If you'd like to reach me via email, please use the email form below, or see the email address. You can also add a comment on any of the posts here at GrantBarker.com.</p><?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?><div id='contact_form_errorloc' class='err'></div>
        <form method="post" name="contact_form" id="contact-form" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" >
			<div>
				<label for="name">
					<span>Your Name (required)</span></label>
					<input type="text" name="name" autofocus value="<?php echo htmlentities($name) ?>">
				
			</div>
			<div>
				<label for="email">
					<span>Your Email (required)</span></label>
					<input type="email" name="email" value="<?php echo htmlentities($visitor_email) ?>" >
				
			</div>
            <div>
				<label for="message">
					<span>Your Message</span></label>
					<textarea name="message" ><?php echo htmlentities($user_message) ?></textarea>
				
			</div><div><p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" class="scalable" id="captchaimg" ><br><br>
<label for="message">Spam blocker. Please enter the above code here :</label> 
<small>Can't read the image? <a href="javascript: refreshCaptcha();" class="blue">Click here to refresh</a>.</small><br>
<input id="6_letters_code" name="6_letters_code" type="text" class="textfield2"><br>

			</p>
				<button type="submit" value="Submit" name="submit">Send it!</button>
			</div>
		</form>
        <img src="images/grant-barker.jpg" alt="" width="200" height="200" class="scalable" title="Grant Barker"/>
        <p><a href="mailto:grant@grantbarker.com"><img src="images/email.png" alt="email" width="190" height="28" class="scalable" title="email Grant"/></a></p>
         <script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator  = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();

frmvalidator.addValidation("name","req","Please provide your name"); 
frmvalidator.addValidation("email","req","Please provide your email"); 
frmvalidator.addValidation("email","email","Please enter a valid email address"); 
  </script>
<script language="JavaScript" type="text/javascript">
function refreshCaptcha()
{
	var img = document.images['captchaimg'];
	img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}</script><p id="back-top"><a href="#top"><span></span></a></p>
      </div><div class="baseline">©2017 GrantBarker.com | <a href="about/grantbarker-com" title="About GrantBarker.com">About</a> | <a href="contact.php" title="Contact Grant Barker">Contact</a></div>
    </div><div class="sidebar">
        <div class="content p7ehc-1"><div class="searchbox"><form method="post" id="searchfield" action="searchresults.php">
<div><input type="text" class="txt" name="search" id="s" value="Search" onfocus="if(this.value == 'Search') {this.value=''}" onblur="if(this.value == ''){this.value ='Search'}" required/></div><button type="submit"  id="searchsubmit" title="Search GrantBarker.com"></button>
</form></div><a href="https://www.grantbarker.com"><img src="images/home.png" alt="Home button" width="26" height="26" class="homebtn" title="Home"/></a>
          
<a href="contact.php"><img src="images/contact.png" alt="Image of envelope" width="42" height="26" class="mailb" title="Contact Grant"/></a>        

        </div>
      </div>
  </div>
</div>
<script src="https://apis.google.com/js/platform.js" async defer></script>
  
<script>
$(document).ready(function(){

	// hide #back-top first
	$("#back-top").hide();
	
	// fade in #back-top
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 100) {
				$('#back-top').fadeIn();
			} else {
				$('#back-top').fadeOut();
			}
		});

		// scroll body to 0px on click
		$('#back-top a').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});
	});

});
</script>
  
  </body>
</html>

Edited by Grant Barker

Share this post


Link to post
Share on other sites

I put it here and it doesn't seem to: You can try it if you like.

</p> <?php echo "Code: " . $_SESSION['6_letters_code']; ?><button type="submit" value="Submit" name="submit">Send it!</button> </div>
Edited by Grant Barker

Share this post


Link to post
Share on other sites

Does it print out just "Code : " with no actual code? If so then the $_SESSION is not set or is empty; which would be why it doesn't match.

 

So either the session is not set, or the session variable is not set, we can test this which should give you a message about things that are set or not.

<?php
$msg = "Message:";
if(session_id()=="") { // Session ID will exist if session is set, if it's emtpy ...
    session_start(); // Start the session.
    if(session_id()=="") { // If it's still not set.
        $msg .= "<br>I can't start session.";
    } else {
	$msg .= "<br>Session is set.";
    }
    if(!isset($_SESSION['6_letters_code'])) { // If $_SESSION['6_letters_code'] is not set.
        $msg .= "<br>6_letters_code is not set.";
	$_SESSION['6_letters_code'] = ""; // Set $_SESSION['6_letters_code']
	if(!isset($_SESSION['6_letters_code'])) { // If it's still not set.
            $msg .= "<br>6_letters_code cannot be set.";
	}
    } else {
	$msg .= "<br>6_letters_code is set.";
        if(trim($_SESSION['6_letters_code'])=="") { // If it's set but empty.
            $msg .= "<br>6_letters_code is empty.";
	} else {
            $msg .= "<br>6_letters_code is " . $_SESSION['6_letters_code'] . ".";
	}
    }
}
echo "<p>" . $msg . "</p>";
?>
Edited by BrowserBugs

Share this post


Link to post
Share on other sites

Yes, it was just printing out "Code : " with no actual code.

The next script also didn't do anything at all.

 

I think it may be server side? I tried uploading older backup versions of the page and they also failed the same way.

 

Could it be related to my server php file and settings?

 

php.png

 

 

Here is the php.ini file (7.1) which I haven't done anything to:

 

EDIT: Sorry. It seems to be OK if I go back to PHP 5.5.

 

I've cleared the cache in a few browsers and it seems to work now. Feel free to try it anyone if you want to check.

My server (ipage) uses the default of PHP 5.5. I must have screwed up by changing to 5.6 quite a while ago.

I'm still not 100% sure, but it seems to be OK at the moment.

Please let me know if you happen to test it and it fails.


Edited by Grant Barker

Share this post


Link to post
Share on other sites

 

EDIT: Sorry. It seems to be OK if I go back to PHP 5.5.

 

I've cleared the cache in a few browsers and it seems to work now. Feel free to try it anyone if you want to check.

My server (ipage) uses the default of PHP 5.5. I must have screwed up by changing to 5.6 quite a while ago.

I'm still not 100% sure, but it seems to be OK at the moment.

Please let me know if you happen to test it and it fails.

 

Ah, didn't know you had changed to 7.1. I think most of the hosts I use stop at 7 at the mo, I've not got any projects in a 7 environment yet so no idea what should be in the ini, most are in the 5.6 bracket. There will also no doubt be some deprecated features from versions gone by.

Share this post


Link to post
Share on other sites

With the greatest respect, why on earth are you writing captcha code?

 

Why not use a captcha that is secure and used all over the web. It's not only more secure, but less intrusive for users.

 

I present :rolleyes:

Share this post


Link to post
Share on other sites

With the greatest respect, why on earth are you writing captcha code?

 

Why not use a captcha that is secure and used all over the web. It's not only more secure, but less intrusive for users.

 

I present :rolleyes:

 

Sorry, I didn't see this thread for a while. I'm not writing any specific captcha code myself. (I wouldn't get any respect at all for that) I was given the captcha code by someone else (in this forum I think) and just implemented it. The issue in this thread was resolved (for now), by switching my site PHP settings back to the PHP version that my host server uses. Thanks. I'm not so advanced, so I kind of fix each issue when I come to it and have the time, although I do enjoy it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing

    No registered users viewing this page.

  • Member Statistics

    • Total Members
      58,433
    • Most Online
      4,970

    Newest Member
    f9ariel
    Joined
  • Forum Statistics

    • Total Topics
      65,748
    • Total Posts
      452,965
×