Friday, February 1, 2013

How To SetUp Recaptcha using PHP

reCAPTCHA is a free CAPTCHA service that helps protect your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration, etc. Below you can find instructions on how to add reCAPTCHA to your site.

Part 1: Sign Up

First, you'll need to sign up and create reCAPTCHA keys for your site. The keys are unique to your domain and sub-domains and will not work for other domains unless you:
  • Sign up for multiple keys (one for each site)
  • Create a global key by checking the box for "Enable this key on all domains (global key)"
For example:
  • The keys for test.com will work on a.test.comb.test.comc.test.com and any other sub-domains.
  • If the option "Enable this key on all domains (global key)" is checked, the keys will work on a.test.comx.comy.com and any other domains or sub-domains.

Part 2: Installation

Installation consists of two steps and optionally a third step where you customize the widget:
  1. Client Side: Displaying the reCAPTCHA Widget (Required)
  2. Server Side: Verifying the solution (Required)
  3. Customizations (Optional)
In most Web forms, you usually have two files: the form itself with the fields and the file with the script to process the inputs to the form. These two files correspond to steps 1 and 2 above. Therefore, in most cases you will have to modify two different files. Displaying the reCAPTCHA widget is the simpler step. You can usually display it using an application plugin (recommended; see below), or alternatively by adding the javascript below inside your <form> element (a third option, discussed later, is to use the AJAX API.)
 <script type="text/javascript"
   src="https://www.google.com/recaptcha/api/challenge?k=YOUR_PUBLIC_KEY"
 </script>
 <noscript>
   <iframe src="https://www.google.com/recaptcha/api/noscript?k=YOUR_PUBLIC_KEY"
       height="300" width="500" frameborder="0"></iframe><br>
 </noscript>
You need to replace the two instances of YOUR_PUBLIC_KEY with the public key that you received during the account creation process (part 1 above). Be careful that you don't use your private key by mistake. Verifying the solution is a bit more difficult, and usually requires modifying a script. Download the 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.

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 <form> 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:
<!-- 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><br>
<!-- more of your HTML content -->
Don't forget to set $publickey by replacing YOUR_PUBLIC_KEY with the value you obtained in Part 1 above. 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 require_once 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: require_once('captcha/recaptchalib.php'). 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.

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:
  • recaptcha_check_answer 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->is_valid 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 recaptcha_get_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. That's it! reCAPTCHA should now be working on your site.

Part 3: Customizing Look and Feel

Now that you've successfully installed reCAPTCHA on your site, you may want to change the way it looks. There are two ways to do this: (1) choosing one of the standard reCAPTCHA themes, or (2) fully customizing the appearance of reCAPTCHA.

Standard Themes

The first step is to add the following code in your main HTML page anywhere before the <form> element where reCAPTCHA appears:
<script type="text/javascript">
var RecaptchaOptions = {
   theme : 'THEME_NAME'
};
</script>
Note: This will not work if it appears after the main script where reCAPTCHA is first invoked. To use a standard theme, you need to replace THEME_NAME by one of the following four theme names:
  • red (default theme)
  • white
  • blackglass
  • clean
 

Custom Theming

To use a fully custom theme, you will need to tell reCAPTCHA that it should not create a user interface of its own. reCAPTCHA will rely on the presence of HTML elements with the following IDs to display the CAPTCHA to the user:
  • An empty div with ID recaptcha_image. This is where the actual image will be placed. The div will be automatically set to 300x57 pixels.
  • A text input with ID and name both set to recaptcha_response_field. This is where the user can enter their answer.
  • A div that contains the entire reCAPTCHA widget. The ID of this div should be placed into the parameter custom_theme_widget of RecaptchaOptions, and the style of the div should be set to display:none. After the reCAPTCHA theming code has fully loaded, it will make the div visible. This element avoids making the page flicker while it loads.
To implement all of this this, first place the following code in your main HTML page anywhere before the <form> element where reCAPTCHA appears:
<script type="text/javascript">
var RecaptchaOptions = {
   theme : 'custom',
   custom_theme_widget: 'recaptcha_widget'
};
</script>
Then, inside the <form> element where you want reCAPTCHA to appear, place:
<div id="recaptcha_widget" style="display:none">
  <div id="recaptcha_image"></div>
  <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect please try again</div>
  <span class="recaptcha_only_if_image">Enter the words above:</span>
  <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>
  <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
  <div><a href="javascript:Recaptcha.reload()">Get another CAPTCHA</a></div>
  <div class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')">Get an audio CAPTCHA</a></div>
  <div class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')">Get an image CAPTCHA</a></div>
  <div><a href="javascript:Recaptcha.showhelp()">Help</a></div>
</div>
<script type="text/javascript"
   src="http://www.google.com/recaptcha/api/challenge?k=YOUR_PUBLIC_KEY">
</script>
<noscript>
  <iframe src="http://www.google.com/recaptcha/api/noscript?k=YOUR_PUBLIC_KEY"
       height="300" width="500" frameborder="0"></iframe><br />
  <textarea name="recaptcha_challenge_field" rows="3" cols="40">
  </textarea>
  <input type="hidden" name="recaptcha_response_field"
       value="manual_challenge" />
</noscript>
Notice that the last few lines are simply the standard way to display reCAPTCHA explained at the beginning of this document. Here's what's going on in the code above. The Recaptcha JavaScript object provides methods which allow you to change the state of the CAPTCHA. The method reload displays a new CAPTCHA challenge, and the method switch_type toggles between image and audio CAPTCHAs. In order to create a full UI for reCAPTCHA, we display different information when the CAPTCHA is in different states. For instance, when the user is viewing an image CAPTCHA, a link to "Get an audio CAPTCHA" is shown. Four CSS classes are available for you to create a stateful UI:
  • recaptcha_only_if_image, visible when an image CAPTCHA is being displayed
  • recaptcha_only_if_audio, visible when an audio CAPTCHA is being displayed
  • recaptcha_only_if_incorrect_sol, visible when the previous solution was incorrect
  • recaptcha_only_if_no_incorrect_sol, visible when the previous solution was not incorrect
While theming does give you many options, you need to follow some user interface consistency rules:
  • You must state that you are using reCAPTCHA near the CAPTCHA widget.
  • You must provide a visible button that calls the reload function.
  • You must provide a way for visually impaired users to access an audio CAPTCHA.
  • You must provide alt text for any images that you use as buttons in the reCAPTCHA widget.

Part 4:Troubleshooting

For troubleshooting, check out the official troubleshooting guide. If that doesn't help answer your question, try asking on the public reCAPTCHA support forum. Hope that it will be useful. If you want any help regarding this please let me know by posting a comment below.

No comments:

Post a Comment