How to create CAPTCHA using PHP

October 05, 2009

Edit: Updated code is posted here: http://superiorwebsys.com/92-make-php-captcha-more-secure/

In last article I explained what CAPTCHA is and why it is used (you can find more information about CAPTCHA here). Here I will provide PHP code that crates and uses CAPTCHA..

Here is sample output of this code:
CAPTCHA
For this you will need 2 files:
LHANDW.TTF – file with the font (click here to download)
secureImage.php – PHP code that creates and displays and image
Here is source of secureImage.php:

<?
session_start
();
header("Content-type: image/png"
);
$_SESSION["secureNumber"]=""
;
//Size of the image Width, Height
$im imagecreate(10520
);        
//Set background color
imagecolorallocate($im167218239
); 
$grey imagecolorallocate($im128128128
);
$black imagecolorallocate($im000
);        
// You can replace fornt by your own
$font 'LHANDW.TTF'
;        
for(
$i=0;$i<=5;$i
++) {
    
$numb=rand(09
);
    
$_SESSION["secureNumber"].=$numb
;
    
$angle=rand(-2525
);
    
imagettftext($im9$angle8+15*$i13$black$font$numb
);    
    
// Add shadow to the text    
    
imagettftext($im9$angle9+15*$i14$grey$font$numb
);    
}
imagepng($im
);
imagedestroy($im
);
?>

How to use this code

1. Display CAPTCHA and input field

<table border="0" cellpadding="0" cellspacing="0">
<tr>
    <td valign="top"><input name="secretNumber"  value="" maxlength="6" /></td>
    <td valign="bottom">
        <img src="/blog/posts/55/secureImage.php" alt="CAPTCHA" />
    </td>
</tr>
</table>

2. Check if correct number was entered

<?
if(!empty($_POST["secretNumber"]) &&
    
$_SESSION["secureNumber"]==$_POST["secretNumber"])
{
    
//Correct number is entered
}
{
    
//Display error message
}
?>

Using CAPTCHA will help to solve refresh problem (You can read about refresh problem here)

In following posts I will provide C# code for CAPTCHA.

Michael Pankratov