PHP Image Captcha verification scriptNote from Bill (admin): this post used to contain a link to a script on another site, but I noticed it's gone so I am replacing the post with a very basic Captcha script I made for a small custom forum.
// If the user's session data does not have a secret captcha phrase, generate and save one. As you can see, it just generates 3 random numbers, but the phrase can be anything you want if you modify it. If you make it something longer, remember to edit the captcha image pixel size.
$_SESSION['secret'] = rand(0, 9) . rand(0, 9) . rand(0, 9);
// Initializes an image with the dimensions of 40x26.
$captcha = imagecreate(40, 26);
// Prints the secret phrase to the image.
imagecolorallocate($captcha, 0, 0, 0);
imagestring($captcha, 5, 7, 4, $_SESSION['secret'], imagecolorallocate($captcha, 255, 255, 255));
// Changes the content-type of this script to a JPG image and output the pixels.
Simply use captcha.php as you would a normal image, for example by adding <img src="captcha.php" alt="Captcha - enter the numbers into the text field" /> next to the captcha input field in your form.
Then, in the script that processes your form, add the code below. Note that the this example script assumes that you named the captcha input field captcha and that the form is set to submit as POST.
// Starts the session. If your form processing script already does this, remove these two lines.
if (empty($_POST['captcha']) || empty($_SESSION['secret']) || $_POST['captcha'] != $_SESSION['secret'])
echo'You must validate that you are a human by entering the correct captcha phrase seen in the little image next to the relevant field. Please go back and try again.';
// The visitor has supplied his idea of what the captcha image contained and it was correct!
// The following code deletes the secret phrase from the session, so that the next time we want him to captcha validate, a new secret phrase will be generated.
Obviously the above is just an example, you should modify it to fit your needs. The important thing is to check that the captcha input field matches the secret phrase in the session data.