Sunday, November 14, 2010

PHP: Effortless CAPTCHA

Include the following code in your form action reciever:


<?
$verif_box = $_POST["verif_box"];
    if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
                      //they got the CAPTCHA correct
                      setcookie('tntcon','');
   }else{
                    //they did not get CAPTCHA correct
   }
?>



Here is a snippet of the part of the form that displays the CAPTCHA:

<tr>

<td valign="top">Type number you see:</td><td valign="top">

<input name="verif_box" type="text" id="verif_box" style="padding:2px; border:1px solid #CCCCCC; width:180px; height:14px;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px;"/>

<img src="verificationImage.php?<?php echo rand(0,9999);?>" alt="verification image, type it in the box" width="50" height="24" align="absbottom" /><br />

<!-- if the variable "wrong_code" is sent from previous page then display the error field -->

<?php if(isset($_GET['wrong_code'])){?>

<div style="border:1px solid #990000; background-color:#D70000; color:#FFFFFF; padding:4px; padding-left:6px;width:295px;">Wrong verification code</div><br />

<?php ;}?>

</td><td>

<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Submit">

</td>



Contents of verificationImage.php:



// -----------------------------------------
//  The Web Help .com
// -----------------------------------------
<?
header('Content-type: image/jpeg');

$width = 50;
$height = 24;

$my_image = imagecreatetruecolor($width, $height);

imagefill($my_image, 0, 0, 0xFFFFFF);

// add noise
for ($c = 0; $c < 40; $c++){
    $x = rand(0,$width-1);
    $y = rand(0,$height-1);
    imagesetpixel($my_image, $x, $y, 0x000000);
    }

$x = rand(1,10);
$y = rand(1,10);

$rand_string = rand(1000,9999);
imagestring($my_image, 5, $x, $y, $rand_string, 0x000000);

setcookie('tntcon',(md5($rand_string).'a4xn'));

imagejpeg($my_image);
imagedestroy($my_image);
?>

1 comment:

Unknown said...

I am about to finish a site where I want to enforce human entry. This is a great resource! Now i can create my own Captcha Code