CAPTCHA using PHP

Today, we had a knowledge sharing session at Eaton. One of our team-mates, Chandraprakash (CP) gave a talk on CAPTCHA.

For those of you who don’t know, CAPTCHA is the image which you see on sign-up forms (pictured below). It helps preventing bots from running scripts and ensures that the form is being submitted by a human and not by some script. Basically, it is used as a security measure for web forms.

CAPTCHA

Example of CAPTCHA

Interesting thing to note is that everytime you enter a captcha, you are contributing to a cause. Yes, the words entered are used to digitize books! Waste of human time being compensated with some cause šŸ˜‰

Here’s how you can implement it using PHP:

Step 1: Download the library file for PHP from here.

Step 2: Create your public and private keys. If you have a domain, give your domain name, else just give “localhost” as the domain if you are using it for testing purpose. Click here to create keys.

Step 3: Client side code:

Make an index.php and insert this code:

<html>
<body>
<form method=”post” action=”verify.php”>
<?php
require_once(‘recaptchalib.php’);
$publickey = “your_public_key”; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<input type=”submit” />
</form>
</body>
</html>

Replace your_public_key with the public key for your domain.

Step 4: Server side code:

Make a file called verify.php and add the code below:

<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die (“The reCAPTCHA wasn’t entered correctly. Go back and try it again.” .
“(reCAPTCHA said: ” . $resp->error . “)”);
} else {
echo “Success”;
//your code on success
}
?>

Again, replace your_private_key with the private key for your domain.

The code is quite self-explanatory I guess. So that’s pretty much of it! Here’s how it will look šŸ™‚

A screenshot of CAPTCHA on my local server

A screenshot of CAPTCHA on my local server

Leave a comment