Use reCAPTCHA in your PHP Scripts

26 11 2010

With reCAPTCHA, you can easily provide captcha on you php powered sites. Simply follow the steps –

1. First you need to download reCAPTCHA PHP library, there you will find a php file named recaptchalib.php, which we will include later in our scripts.

2. Then sign up for API keys for your site. If you are planning to use the same key over all sub-domains, then you can enable the ‘global key’ option while signing up. You will be given a public key and a private key. Public key is for use in html/javascript code, that is served to end users. And private key is used in processing part, for communicating between your server and reCAPTCHA server.

3. Now time to show the captcha image in your site, just put the code block below inside the form tag where you wish captcha image to display –

require_once('recaptchalib.php');
$publickey = "your_public_key"; // you got this from the signup page
echo recaptcha_get_html($publickey);

4. And finally you need to verify the user input against the captcha image displayed, the following code block is responsible for that –

<?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 was incorrect, try it again.");
  } else {
    // Your code here to handle a successful verification
  }
?>

Thats all, it will surely save you from few hours of coding if were doing all this from scratch.

Advertisements