How to Create a CAPTCHA with PHP

CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use CAPTCHA on your web site forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms.

So, you have a public submission form on your website (contact page, forum submission) and need to prevent spam auto-submitters. A common way to do this is to implement CAPTCHA – an image with a randomly generated string.

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.

Please follow the steps to generate captcha generaion

1) Make a PHP script (separate file captcha.php) which will generate the image:

<?

session_start();

$md5_hash = md5(rand(0,999));
//We don’t need a 32 character long string so we trim it down to 5
$string = substr($md5_hash, 15, 4);

$_SESSION[‘rand_code’] = $string;

$dir = ‘./style/font/’;
$width=125;
$height=30;

$image = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 35, 155, 240);
$white = imagecolorallocate($image, 255, 255, 255);
$noise = imagecolorallocate($image, 0, 138, 187);

imagefilledrectangle($image,0,0,399,99,$white);

// add noise
for ($c = 0; $c < 40; $c++){

$x = rand(0,$width-1); $y = rand(0,$height-1); imagesetpixel($image, $x, $y, $noise);

}

//imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

imagettftext ($image, 25, 0, 5, 27, $color, $dir.”AFPEPSI.TTF”, $_SESSION[‘rand_code’]); header(“Content-type: image/png”); imagepng($image);

?>

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):

<?php session_start() ?>
<img src=”captcha.php” alt=”captcha image”>
<?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’;
}
?>

Permanent link to this article: https://blog.openshell.in/2011/01/how-to-create-a-captcha-with-php/

Leave a Reply

Your email address will not be published.