encaps.net
Search in:

How to implement CAPTCHA with PHP and GD

So, you have a public submission form on your website (contact page, forum submission):

Contact us (Post new message):

<form method="post" action="">
<table>
<tr><th>Contact us (Post new message):</th></tr>
<tr><td><textarea cols="20" rows="5"></textarea></td></tr>
<tr><td><center><input type="submit" value="Submit"></center></td></tr>
</table>
</form>

and need to prevent spam auto-submitters. A common way to do this is to implement CAPTCHA – an image with a randomly generated string: captcha image
(from Wikipedia, free online encyclopedia: “A CAPTCHA is a type of challenge-response test used in computing to determine whether the user is human. “CAPTCHA” is an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart”, trademarked by Carnegie Mellon University.”)

Simple, quick and efficient PHP solution for implementing CAPTCHA:

the advantage of this solution: it is easy to read symbols by human and automated CAPTCHA processor software, but hard to process the image by computer because common CAPTCHA processors can’t understand which one of the output symbols it must ignore!

Obviously you need a PHP engine enabled for your Web server to execute PHP scripts, and GD (PHP graphics library) to generate the image. The solution below is tested for Apache (Windows and Unix), IIS (Windows), PHP-4, PHP-5, GD and GD2.
1) Make a PHP script (separate file captcha.php) which will generate the image:
<?php
session_start();
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

function _generateRandom($length=6)
{
$_rand_src = array(
array(48,57) //digits
, array(97,122) //lowercase chars
//        , array(65,90) //uppercase chars
);
srand ((double) microtime() * 1000000);
$random_string = “”;
for($i=0;$i<$length;$i++){
$i1=rand(0,sizeof($_rand_src)-1);
$random_string .= chr(rand($_rand_src[$i1][0],$_rand_src[$i1][1]));
}
return $random_string;
}

$im = @imagecreatefromjpeg(“captcha.jpg”);
$rand = _generateRandom(3);
$_SESSION[‘captcha’] = $rand;
ImageString($im, 5, 2, 2, $rand[0].” “.$rand[1].” “.$rand[2].” “, ImageColorAllocate ($im, 0, 0, 0));
$rand = _generateRandom(3);
ImageString($im, 5, 2, 2, ” “.$rand[0].” “.$rand[1].” “.$rand[2], ImageColorAllocate ($im, 255, 0, 0));
Header (‘Content-type: image/jpeg’);
imagejpeg($im,NULL,100);
ImageDestroy($im);
?>

2) Add the following line at the top of the page where you need to implement CAPTCHA:
<?php session_start() ?>

3) Add the following line to check whether the CAPTCHA string entered by the visitor is valid, before the line where you will proceed with a submitted message:
<?php
if($_SESSION["captcha"]==$_POST["captcha"])
{
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
}
?>

4) Finaly add the CAPTCHA to the form:

Contact us (Post new message):
CAPTCHA:
(antispam code, 3 black symbols)
captcha image
<?php session_start() ?>
<form method="post" action="">
<table bgcolor="#CCCCCC">
<tr><th colspan="2">Contact us (Post new message):
</th></tr>
<tr><td colspan="2">
<textarea cols="30" rows="5" name="message">
</textarea></td></tr>
<tr><td colspan="2"><center>CAPTCHA:
(antispam code, 3 black symbols)</center></td>
</tr><tr>
<td><img src="../software/captcha.php" alt="captcha image" />
</td>
<td>
<input type="text" name="captcha" 
size="3" maxlength="3" /></td></tr>
<tr><th colspan="2"><center><input 
type="submit" value="Submit" /></center></th>
</tr>
</table>
</form>
<?php
if(isset($_POST["captcha"]))
if($_SESSION["captcha"]==$_POST["captcha"])
{
//CAPTHCA is valid; proceed the message: save to 
//database, send by e-mail ...
echo 'CAPTCHA is valid; proceed the message';
}
else
{
echo 'CAPTCHA is not valid; ignore submission';
}
?>