[Tutorial] Basic Usage of reCAPTCHA with PHP

In this tutorial we will be installing a reCAPTCHA script from Google on to your website.  This script will help stop spam and actually works for a good cause as it digitizes books.

Step 1 – Setup/Install

To start off, you will need to download the latest reCAPTCHA library file from their website.
Click Here to Download Latest Library Files »

Once downloaded, go ahead and extract the compressed file to your desktop (or somewhere you can remember).  You only need to copy the recaptchalib.php file to your server, the other files are not needed.

You can upload recaptchalib.php using FTP (we recommend FileZilla) or any other method such as a file manager through your hosting provider (such as cPanel).

In order to use reCAPTCHA, you need to create an API key to use this service.  Once you have acquired your public and private key be sure to write them down as you will need both in future steps.  You can click the link below to register for an API key.
Create a reCAPTCHA Key »

Now that our library file is uploaded and we have an API key, we are ready to move on to the next step.


Step 2 – Displaying reCAPTCHA

Now that we have uploaded the required library, it is time to begin our script.  Below we are going to create a script that displays the reCAPTCHA to your users.  We are going to name this file form.php and enter the following code.

<form method="post" action="check.php">
<?php
require_once('recaptchalib.php'); // reCAPTCHA Library
$pubkey = ""; // Public API Key
echo recaptcha_get_html($pubkey); // Display reCAPTCHA
?>
<input type="submit" value="Check" />
</form>

Be sure to enter the correct location of recaptchalib.php within the function require_once().  Next, copy your new public API key that you received from reCAPTCHA and enter that key between the quotes for the variable $pubkey.  The PHP function recaptcha_get_html() is function from recaptchalib.php that holds the code to display the reCAPTCHA script.

NOTE: recaptcha_get_html() will only return the HTML code to display the reCAPTCHA as a variable, it will not actually print the code for a user to see.  This is why we must use PHP function echo() so the HTML code is presented to the user.

By using the code above, after making your changes such as updating the location of recaptchalib.php and entering your public API key, you are now displaying a working reCAPTCHA.  The next step is the verify if the user has entered each word correctly.


Step 3 – Checking the reCAPTCHA

Now that we have a working reCAPTCHA, we now need to verify if the user correctly entered the displayed words.  This second file will now be named check.php so it can complete the task of verifying the response compared to the correct answer from the reCAPTCHA.

<?php
require_once('recaptchalib.php'); // reCAPTCHA Library
$privkey = ""; // Private API Key
$verify = recaptcha_check_answer($privkey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
 
if ($verify->is_valid) {
  # Enter Success Code
  echo "Your response was correct!";
}
else {
  # Enter Failure Code
  echo "You did not enter the correct words.  Please try again.";
}
?>

Once again, make sure require_once() is pointing to the correct location of recaptchalib.php on your server.  Make sure you insert your private API key (not the public API key) between the quotes for the variable $privkey.

Then the function recaptcha_check_answer() will use the private API key, the user’s IP address, and the user’s answer to see if it was correct compared to the reCAPTCHA displayed on the previous page.

To determine if the response was answered correctly, $verify->is_valid will be true if the answer was correct, or false if the answer was incorrect.  If the answer was incorrect, you could also use $verify->error to determine what was the issue.

You can now add whatever code you want performed depending on whether the responses were correct or incorrect.


Step 4 – Combining To A Single File

This final step is optional, so it is not required in order to make this script functional.  The purpose of this additional step is to demonstrate the possibility that the functions of both files could all be performed within a single file named verify.php.

<?php
require_once('recaptchalib.php'); // reCAPTCHA Library
$pubkey = ""; // Public API Key
$privkey = ""; // Private API Key
 
if ($_POST['doVerify']) {
  $verify = recaptcha_check_answer($privkey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
  if ($verify->is_valid) {
    # Enter Success Code
    echo "Your response was correct!";
  }
  else {
    # Enter Failure Code
    echo "You did not enter the correct words.  Please try again.";
  }
}
?>
<div>
<form method="post" action="verify.php">
<?php echo recaptcha_get_html($pubkey, $verify->error); ?>
<input type="submit" name="doVerify" value="Verify" />
</form>
</div>

So there you have it. A complete reCAPTCHA script all fit within a single PHP file.  Be sure to make the adjustments to the location of recaptchalib.php in require_once() as well as inserting both public and private API keys.

Remember this step is optional and is not required for normal functionality.


Conclusion

So now you have seen how to properly setup the reCAPTCHA library file, recaptchalib.php, as well as creating an API key.  After setup, we covered how to present the reCAPTCHA HTML code to the user followed by a method on how to verify the answer.  Lastly we saw that it was possible to go ahead and merge all that code in to a single file.

I hope you enjoy using the reCAPTCHA service as it is an amazing tool to block spam and help digitize books.  It is a good-good scenario that you cannot beat.

This entry was posted in PHP Tutorials, Tutorials and tagged , by Brandon Enriquez. Bookmark the permalink.

About Brandon Enriquez

Brandon has been around Prosoft Studio since the very beginning of the company back in the summer of 2007. As the founding member, he has laid out a vision of providing the best professional software and offering methods of teaching others some of his own knowledge. He is very experienced in (X)HTML, CSS, JavaScript, PHP, and SQL programming languages. He is also experienced in Adobe Photoshop for website design and graphic designs such as logos, banners, and other media.
  • http://www.designid.com.au/ design id

    Any idea where I’m going wrong – my captcha shows but is by bypassed. I’ve set up my verify.php correctly but its not verifying 


                         
     var RecaptchaOptions = {
        theme : ‘blackglass’
     };
      
                         
                          
                             
                             
                              
                             
                              
                             
                             
                             
                              Message*
                             
           

                             

                         
                         *required