The CAPTCHA Image
We are going to use PHP's GD image library to generate the image used in the Ajax CAPTCHA, then we can display it in our IMG element like this:
src="captcha.php"
For simplicity here we're going to import a background image to use with our CAPTCHA. Here's the code at the start of captcha.php:
session_start();
$captcha = imagecreatefrompng('captcha.png');
The first line establishes a PHP session; this lets us store variables that will be available to all scripts for the life of the browser session. Next, we use the GD library to extract the background image from our external file, and store it in the variable $captcha.
Now we need to generate a random string, add it to our image, and store the string in a session variable so we can later test it against the user's input:
$charlist = '23456789ABCDEFGHJKMNPQRSTVWXYZ';
These are the characters we'll allow in the CAPTCHA. We avoid O, 1 etc to avoid confusion over letters and numbers.
$chars = 5;
$i = 0;
while ($i < $chars)
{
$string .= substr($charlist, mt_rand(0, strlen($charlist)-1), 1);
$i++;
}
The first line in the above code snippet sets the number of characters in our string. The following while loop, on each pass, chooses on character at random from our $charlist. We now have a variable $string containing a random 5-character string - we want to store this in a session variable, and add it to our background image:
$_SESSION['secret_string'] = $string;
imagettftext($captcha, 17, 0, 13, 22, $grey, 'Whimsy.TTF', $string);
Note that we are using a TTF font to do this. There are easier ways to output a string, but choosing an unusual font can help to make it harder for machines to read the text.
Finally, we need to output the image to our HTML page:
header("Content-type: image/png");
imagepng($captcha);
That's that - we have our image on the form, with a random character string which we've saved to check against user input.
This site is brand new and so still somewhat under construction.
Why not bookmark it and call back regularly?