Friday, 14 September 2007

Use CAPTCHA to protect sites from abuse - PHP Approach

First thing first, lets take a look at CAPTCHA's physical appearance (a screenshot from my application) :

Ah... CAPTCHA is a program to tell whether the user is a human or a computer.

Secondly, CAPTCHA is very very secure as it uses two layers of protection when generating the image. It starts with images that can't be read by computers, and then distorts them even more as shown in the screenshot above. The OCR software read the image (screenshot above) as "ibataz Iueqm". :-)

Now, Lets implement it by using PHP:

Step One: Display the image

$publickey = "xxxxxxxxxxxxxxxxxxxxxxxx";
$capImg = recaptcha_get_html($publickey);
echo $capImg; //Display the image

Step Two: Check if the user input is correct
The reason to use $_SESSION['Code'] is to stop checking it again if the last attempt was correct. For example, you need a user to specify a valid email address AND to get this image correct. But, he forgot to put his email ... So, he only need to tell you what his email address is on the next screen.
if ($_SESSION['Code'] != "yes") // user's last input was correct
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$resp = recaptcha_check_answer ($privatekey,

if (!$resp->is_valid)
$_SESSION['Code'] = "no";
} else {
$_SESSION['Code'] = "yes";

Step Three: Display another image if the user's input was incorrect
if ($_SESSION['spamCode'] != "yes")
$Info = "Oops! You got it wrong, please try again ...";
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$capImg = recaptcha_get_html($publickey);
echo $capImg;
} else {
$Info = "Correct!";
echo $Info;

No comments: