reCAPTCHA is a free service by Google that protects your site from spam and other types of automated abuse. It uses advanced risk analysis techniques to tell humans and bots apart.
This tutorial is aimed at people who are familiar with basic PHP and HTML forms. The source code of this tutorial is available here.
Sign up for your API keys reCAPTCHA API keys
To start using reCAPTCHA you will need to register your website to get the reCAPTCHA API key pair from Google. The key pair consists of a site key and a secret key. The site key is used to call or invoke the reCAPTCHA service on your site. The secret key authorizes communication between your application backend and the reCAPTCHA server to verify the user’s response. The secret key needs to be kept safe for security purposes.
Fill in the form and select the reCAPTCHA v2 and in that select “I am not a robot” checkbox option.
Once submitted, Google will provide you with your site key and secret key.
After you’ve signed up for your API keys, below are basic instructions for installing reCAPTCHA on your site. We will be using a simple form as an example.
Adding reCAPTCHA widget
<script src='https://www.google.com/recaptcha/api.js' async defer ></script>
Now we will add the below HTML code to our form where we want the reCAPTCHA widget to appear.
<div class="g-recaptcha" data-sitekey="site_key"></div>
Replace site_key with the actual site key provided by google.
For this tutorial, we will create a simple form to test reCAPTCHA with PHP. Once you are done refresh your page and you will see the reCAPTCHA widget on your site.
<form method="POST"> <div class="g-recaptcha" data-sitekey="site_key"></div> <input type="submit" name="login" value="Log in"> </form>
Validating the user response
You need to validate the response when a user clicks on the reCAPTCHA widget. To verify you need to write some PHP code as below.
Replace google_secret_key with the secret key provided by google.
When the form is submitted, it will send ‘g-recaptcha-response’ as a POST data. You need to verify it to see whether the user has checked the reCAPTCHA or not. We then submit the reCAPTCHA data to google for verification.
$response->success is true then the captcha challenge was correctly completed and you should continue with form processing.
$response->success is false then the user failed to provide the correct captcha you should redisplay the form to allow them another attempt.
Notice that this code is asking for the secret key, which should not be confused with the site key. You get that from the same page as the site key.
The source code of this tutorial is available here.
That’s it for today! reCAPTCHA should now be working on your site.