Using reCAPTCHA with PHP


July 27, 2012

Using reCAPTCHA with PHP

What is Captcha?

A CAPTCHA is a challenge response test used on computers to check if the user is human. A common kind of CAPTCHA that is used on websites requires that the visitor type the letters and numbers of a distorted image. This method is based on the fact that is difficult for computers to extract the text from the image while it is very easy for humans.

They are very common these days because of spammers who create special scripts and programs that automatically submit forms.

Programmers have worked to create special algorithms that can read the distorted letters from images with the purpose of defeating Captcha images.

Strong captcha’s must be used to insure that spam bots will not pass and submit their information to forms

The reCAPTCHA PHP Library provides a simple way to place a CAPTCHA on your PHP website, helping you stop bots from abusing it. The library wraps the reCAPTCHA API.

To use reCAPTCHA with PHP, you can download reCAPTCHA PHP library. You will only need one file from there (recaptchalib.php). The other files are examples, readme and legal stuff — they don’t affect functionality.

Creating a CAPTCHA with PHP

You may be thinking just exactly what is a captcha? Well you are likely to have already seen them across the web. They are those little images with a code on the front that you type into a box in order to submit something. This kind of system helps to prevent automatic submitting of an operation by some kind of program or robot. In this tutorial I will show you how to make a CAPTCHA just like the one below. Its not the most advanced captcha available because it uses a simple system font and nothing more.

The lines that you see above are to make any robots job of trying to work out that code a little harder. The dots in the background also help with this. I will now show you how to create one of these that uses a background file that you can easily change.

Quick Start

After you’ve signed up for your API keys, below are basic instructions for installing reCAPTCHA on your site. A full reference guide to the PHP plugin can be found below.

Client Side (How to make the CAPTCHA image show up)

If you want to use the PHP library to display the reCAPTCHA widget, you’ll need to insert this snippet of code inside the + element where the reCAPTCHA widget will be placed:

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

With the code, your form might look something like this:

  <html>
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

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

      <!-- more of your HTML content -->
    </body>
  </html>

Don’t forget to set $publickey by replacing yourpublickey with your API public key.

Note that the value of the “action” attribute is “verify.php”. Now, verify.php is the destination file in which the values of this form are submitted to. So you will need a file verify.php in the same location as the client html.

The requireonce function in the example above expects recaptchalib.php to be in the same directory as your form file. If it is in another directory, you must link it appropriately. For example if your recaptchalib.php is in the directory called “captcha” that is on the same level as your form file, the function will look like this:requireonce('captcha/recaptchalib.php').

Server Side (How to test if the user entered the right answer) The following code should be placed at the top of the verify.php file:

  <?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 {
    // Your code here to handle a successful verification
  }
  ?>

In the code above:

  • recaptchacheckanswer returns an object that represents whether the user successfully completed the challenge.
  • If $resp->is_valid is true then the captcha challenge was correctly completed and you should continue with form processing.
  • If $resp->isvalid is false then the user failed to provide the correct captcha text and you should redisplay the form to allow them another attempt. In this case$resp->error will be an error code that can be provided to recaptchaget_html. Passing the error code makes the reCAPTCHA control display a message explaining that the user entered the text incorrectly and should try again.

Notice that this code is asking for the private key, which should not be confused with the public key. You get that from the same page as the public key.

Also make sure your form is set to get the form variables using $POST, instead of $REQUEST, and that the form itself is using the POST method.