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(105, 20
);        
//Set background color
imagecolorallocate($im, 167, 218, 239
); 
$grey = imagecolorallocate($im, 128, 128, 128
);
$black = imagecolorallocate($im, 0, 0, 0
);        
// You can replace fornt by your own
$font = 'LHANDW.TTF'
;        
for(
$i=0;$i<=5;$i
++) {
    
$numb=rand(0, 9
);
    
$_SESSION["secureNumber"].=$numb
;
    
$angle=rand(-25, 25
);
    
imagettftext($im, 9, $angle, 8+15*$i, 13, $black, $font, $numb
);    
    
// Add shadow to the text    
    
imagettftext($im, 9, $angle, 9+15*$i, 14, $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