Create a captcha in PHP

We are going to create a CAPTCHA in PHP, for us to do this we need to use a PHP library called GD. The GD library is used to manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM…. with GD you can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work.

Lets create our file then and call it captcha.php

<?php

session_start();

$md5 = md5(microtime() * mktime());

$string = substr($md5,0,5);
$captcha = imagecreatefrompng(“captcha.png”);

$text = imagecolorallocate($captcha, 100, 100, 200);
$line = imagecolorallocate($captcha,233,239,239);

$chararray = str_split($string);
for ($y = 0; $y <= 4; $y++) {
imageline($captcha,rand(0,100),rand(0,50),rand(0,100),rand(0,50),$line);
imageline($captcha,rand(0,100),rand(0,50),rand(0,100),rand(0,50),$line);
imagestring($captcha, 5, (20+($y*10)), (10+rand(-10,10)), $chararray[$y], $text);
}

$_SESSION[‘captcha_code’] = md5($string);

header(“Content-type: image/png”);
imagepng($captcha);

?>

In this code

  1. We started a new session
  2. Got a number related to the time and encrypted it with MD5
  3. Reduced it to 5 characters
  4. Opened the PNG file which we shall draw upon, you would need to create one. I just created a plain white image with dimensions of 100×50(pixels)
  5. Got our text and line colours
  6. looped through each character in the string and added each character in a random y position. Lines were also added, double to the amount of characters, in a random place within the image.
  7. stored the captcha_code into a session variable.
  8. created an image header
  9. load the image

next we need to load and check our CAPTCHA on our index page, so lets create index.php

<?php

session_start();
error_reporting(E_ALL ^ E_NOTICE);

$msg = ”;

if(md5($_POST[‘captchacode’]) != $_SESSION[‘captcha_code’]) {
$msg .= ‘captha code still needed’;
} else {
$msg .= ‘correct captcha code’;
}

echo <<<EOT

<html>

<body>

$msg<br />

<img src=”captcha.php”>

<form method=”POST”>
captchacode”>

<input type=”submit” value=”check”>
</form>

</body>

</html>

EOT;

?>

  1. We started a new session
  2. checked if the CAPTCHA code is equal to the session variable stored within captcha.php
  3. We loaded the PHP file as if it is an image
  4. The rest is self-explanatory

And that is it, you can now put a CAPTCHA in your form to stop you from getting a whole lot of spam coming through.

You may download the example from my website, techfind.co.uk


About this entry