PHP Image Captcha verification script

sandykadam

202.***.***.***
1,832 days ago

PHP Image Captcha verification script

Note 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.

captcha.php:

PHP code:

<?php

@ini_set('url_rewriter.tags', '');
@session_start();

// 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.
if (empty($_SESSION['secret']))
{
$_SESSION['secret'] = rand(0, 9) . rand(0, 9) . rand(0, 9);
}

if(!empty($_SESSION['secret']))
{
// 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.
header('Content-type: image/jpeg');
imagejpeg($captcha);
imagedestroy($captcha);
}

?>



Example usage:

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.

PHP code:

// Starts the session. If your form processing script already does this, remove these two lines.
@ini_set('url_rewriter.tags', '');
@session_start();

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.';
exit;
}
else
{
// 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.
unset($_SESSION['secret']);
}



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.

Bill

84.***.***.***
1,080 days ago
I replaced your post with a little script I wrote, as the link you referenced is dead. Hope you don't mind.

The script is very basic, but easy to understand and doesn't require installation of additional fonts or libraries.