WebDew

How to Integrate Google reCAPTCHA v2.0 with PHP

Google reCaptcha

Spam is a huge problem for website owners at the current moment. Spam is everywhere. But what can we do with it? We have lots of options how to secure our websites; however, the most effective is a use of Captcha. So, what’s the purpose of these strange input fields? The purpose is very clear: fight the spam. In this tutorial I’ll show you the easiest way how to integrate Captcha into your website.┬áThe most popular, powerful, and user-friendly Captcha is a Google Recaptcha.

Step 1: Get Google reCaptcha API keys

You can’t use the reCaptcha on your website without special API keys. To get them go to the official Google Recaptcha website.

Now, register your website.

Google reCapatcha register your website

Once you have registered your website; it’s time to get your site key which is used to display the reCaptcha widget on your web page.

Google Recaptca Site Key

Also don’t forget to get your secret key because your site will use it for communicating with the reCaptcha server.

Google Recaptcha Secret Key

Step 2: Add the Google reCaptcha to your site

Open your website or the page where you want to use the reCaptcha with any text editor (Notepad++ is a good choice). Find your </head> closing tag and insert the following highlighted code:

<head>
 <!-- Here you can find many other tags. Leave them. -->
 <script src='https://www.google.com/recaptcha/api.js'></script>
</head>

Find the form where you would like to place your captcha, and insert the highlighted code:

<form method="post">
 <input type="text" name="username" />
 <input type="password" name="password" />
 <!-- You can have another form structure. It is just an example! -->
 <div class="g-recaptcha" data-sitekey="PLACE YOUR SITE KEY HERE"></div>
 <!-- A good idea to place Captcha before the submit button -->
 <input type="submit">
</form>

Done! But… Wait! We forgot to update the PHP file that proceeds all data from the form! Have a look on the code snippet below, and try to integrate it into your existing code.

$secret_key = '6Lc6YjwUAAAAAKzgGGHAuJAb_thg9ipF2bc2ZiQr'; // Your Google reCaptcha secret key

if(!empty($_POST['g-recaptcha-response']))
{
 // Request the Google server to validate our captcha
 $request = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);
 // The result is in a JSON format. Decoding..
 $response = json_decode($request);

 if($response->success)
 {
  // Here goes your code.
  echo 'Congratulations! You have passed the reCaptcha!';
 }
 else
 {
  echo 'Please, try again. You must complete the Captcha!';
 }
}

Done.

2 Comments

  1. Carlos says:

    Thank you so much it’s work !

  2. Peter K. says:

    Wow, this was easy to implement. Thank you for posting this guide.

Leave a Reply