Protects your site against spam using reCAPTCHA

Course- PHP Tutorial >

Google provide a very secure and easy to use and free anti-bot service know as reCAPTCHA. reCAPTCHA will protect your forms and website from spam. It is very easy to integrated and highly secure. You can also display multiple reCAPTCHA in a single page and validate reCAPTCHA without page refresh using jQuery and AJAX.

How to Get reCAPTCHA

First of all you need to generate your reCAPTCHA API key from here. Google provides you to generate a global key which you can use in any domain or in other words the same key will works in all websites. You can also generate API for single domain. But the API will works for sub domains and child domains. If you have generated an API for www.a2zwebhelp.com then same API will works for products.a2zwebhelp.com and a2zwebhelp.com/products. 
Once you click on "Create Key", in the next page it will display your Public Key and Private Key copy both keys and save in a text file.

How to display reCAPTCHA in PHP page?

Once you get your Public key and Private key you need to download reCAPTCHA library files from here. The Zip folder will provide you an example PHP file and reCAPTCHA library file. Write down the following code in the top part of your PHP file.

<?php
  require_once('recaptchalib.php');
  $publickey = ""; //Enter your public key here.
  $privatekey = ""; ////Enter your private key here
  $resp = null; // the response from reCAPTCHA
  $error = null; // the error code from reCAPTCHA, if any
?>


Write the following code inside your form tag where you want to display reCAPTCHA.

echo recaptcha_get_html($publickey, $error);


Write the following code to  validate reCAPTCHA

if ($_POST["recaptcha_response_field"]) {
    $resp = recaptcha_check_answer ($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);

        if ($resp->is_valid) {
	    // Your code goes here
            echo "You got it!";
        } else {
            # set the error code so that we can display it
            echo $resp->error;
        }
}


How to display Multiple reCAPTCHA in PHP page?

If you want to display multiple reCaptcha in a single page then it can be done through jQuery. You need to put your first reCAPTCHA inside a div and the second reCAPTCHA can be generated in another div with help of jQuery.

Put your first reCAPTCHA in site a div with ID re-CAPTCHA-1 

<div id="reCAPTCHA-1"> 
<?php
echo recaptcha_get_html($publickey, $error);
?>
</div>


Create another div with ID reCAPTCHA-2, place it where you want to display second reCAPTCHA. And write the following jQuery in header part of your HTML page.

<script>
$(document).ready(function() {
// Duplicate our reCapcha 
$('#reCAPTCHA-2').html($('#reCAPTCHA-1').clone(true,true));
});
</script>


Put reCAPTCHA-2 div where you want to display the second reCAPTCHA. No need to print recaptcha_get_html in this div again.

<div id="reCAPTCHA-2"> </div>


How to validate reCAPTCHA in jQuery?

The following code will generate and validate reCAPTCHA using jQuery.

<script type="text/javascript">
function loadRecaptcha() {
     var publicKey = ""; // Enter your public key here.
     var div = "reCAPTCHA-1";
     Recaptcha.create(publicKey,div);
     return false;
}

function validate() {
     var challenge = Recaptcha.get_challenge();
     var response = Recaptcha.get_response();
$.ajax({
     type: "POST",
     url: "validateRecaptcha.php",
     async: false,
     data: {
          challenge: challenge,
          response: response
     },
success: function(resp) {
if(resp == "true") {
    document.getElementById("message").innerHTML = "Correct Captcha!";
}
else {
    document.getElementById("message").innerHTML = "Incorrect Captcha!";
    loadRecaptcha();
}
}
});
return false;
}

$(document).ready(function() {
   loadRecaptcha();
});
</script> 

 

validateRecaptcha.php

<?php
require_once('recaptchalib.php');
$privatekey = ""; // Enter your private key here
$resp = recaptcha_check_answer ($privatekey,$_POST["remoteip"],
        $_POST["challenge"],$_POST["response"]);
if (!$resp->is_valid) {
echo "false";
}
else {
echo "true";
}
?>