Sample Code: PHP Captcha Simple


Problem
: Web form spam or bot induced form submissions  is a common issue these days on we pages that have forms. The simplest way to thwart such spam is to use a captcha. There are many varieties of captcha but today I’m going to focus on some simple code that does the job quickly and easily.

Step 1. You need some code to generate a graphical (image) representation of the captcha . Many PHP installations come with GD enabled, we can use this to generate the graphical captcha. We can call this file php_captcha.php and call it from the web page with the form.

 

<?php
session_start();
$RandomStr = md5(microtime());
$ResultStr = substr($RandomStr,0,5);
$NewImage =imagecreatefromjpeg("img.jpg");

$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imageline($NewImage,1,1,40,40,$LineColor);
imageline($NewImage,1,100,60,0,$LineColor);
//imagestring($NewImage, 5, 20, 10, $ResultStr, $TextColor); 
$font = imageloadfont("font.gdf");
imagestring ($NewImage, $font, 5, 5, $ResultStr, $TextColor ); 
$_SESSION['key'] = $ResultStr;  //store the actual result in a Server session

header("Content-type: image/jpeg");
imagejpeg($NewImage);
?>

 

Step 2. On the web page with the form simply call this captcha ans use the session information to test its validity. First here’s the web page html code for this simplified form.

<html>
<form action="post_form.php" method="post" name="form1">
<img src="php_captcha.php"><br />
<input name="captcha" type="text" id="captcha" size="15">
<br>
Please enter the code shown in the image to 
the left. This is necessary to prevent form 
spam. <br />

<textarea name="message" cols="25" rows="5"></textarea>
<input name="Submit3" type="submit"  value="send mail" >
<input type="reset" name="Submit22" value="clear">
</form>
</html>

Here’s what the sample form looks like

captcha

 

 

Step 3. Finally on the form processing the submission use something like this to validate the captcha.

<?php

//captcha check
      $key=substr($_SESSION['key'],0,5);  //session of captcha
      $number = $_REQUEST['captcha'];
      if($number!=$key)
        print_error("<b> The Code you entered does not match the image shown, Press Back and try again! </b>");

?>