Integrate google reCAPTCHA in your website

Here you’ll learn how to integrate google reCAPTCHA in your website to prevent Spam entry.

What is captcha?

It is a computer program or system intended to distinguish human from machine input, typically as a way of thwarting spam and automated extraction of data from websites.




Google has designed a simple and powerful program to prevent robot spam called google reCAPTCHA, It is easy to integrate in your website in just simple steps.
recaptcha-3

DEMO DOWNLOAD

So Lets start tutorial step by step.

Step-1: Register for google reCAPTCHA, Note before proceeding you must login with your gmail account.
https://www.google.com/recaptcha/admin#list



Step-2: After that you will see below screen, Now enter your captcha label and domain name where you have to show your captcha.
recaptcha-1

Step-3 After filling all the field click on Register button, Then you’ see your Site Key, Secrete Key and some html code snippets, follow the guide and add these code snippets in your website where you have to display your google captcha.
recaptcha-2

After submitting the form IF you haven’t enter captcha then you’ll get the blank response in g-recaptcha-response

Step-4: For server side validation,When your users submit the form where you integrated reCAPTCHA, you’ll get as part of the payload a string with the name “g-recaptcha-response”. In order to check whether Google has verified that user, send a POST request with these parameters:
secret, response, remoteip

Step-5: Verify google reCAPTCHA using php (Server Side).

function verifySite($recaptcha)
{
 $recaptchaAuthUrl="https://www.google.com/recaptcha/api/siteverify";
 $secret='Secret Key';
 $remoteip=$_SERVER['REMOTE_ADDR'];
 $url=$recaptchaAuthUrl."?secret=".$secret."&response=".$recaptcha."&remoteip=".$remoteip;
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_TIMEOUT, 10);
 curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
 $res = curl_exec($curl);
 curl_close($curl);
 return $res;
}

Pass your post g-recaptcha-response data to this function and verify.

$recaptcha = $_REQUEST['g-recaptcha-response'];
$response = verifySite($recaptcha);

In response variable you may get success as true and false. If captcha pass the site authentication it will return success as true if not then it’ll return false.

{
  "success": false,
  "error-codes": [
    "invalid-input-secret"
  ]
}

DEMO DOWNLOAD

You can read more google reCaptcha features from google official document.
https://developers.google.com/recaptcha/intro

Thanks 🙂

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.