Add Google reCAPTCHA V2 to a Website

Google offers a free service called reCAPTCHA to help websites fight against spambots. This reCAPTCHA is integrated into a website as a checkbox to confirm human interaction with the page. Learn how to add Google reCAPTCHA V2 to a website step-by-step.

Add Google reCAPTCHA V2 to a Website

Dealing with spambots can be a headache for website developers and owners. They are designed to post a large number of unwanted content. The content can be a post, comment or a fake account. This can lead to wasted resources of the server. One of many necessary ways to counter this issue is to protect website forms with a reCAPTCHA. This post demonstrates how to integrate "I'm not a robot" checkbox from Google to prevent bot abuse.

 

How to Add Google reCAPTCHA V2 to a Website?

We need to follow a few simple steps to implement the reCAPTCHA V2 checkbox on a website. These steps involve registering a website on Google reCAPTCHA and retrieving the site key and secret key from there. Integrate reCAPTCHA into the website and validate the response on the server side.

 

Step 1: Register The Website on Google reCAPTCHA

The first step is to get the site key and site secret from the Google reCAPTCHA admin to use on our website. Steps to register a website on Google reCAPTCHA are:

  • Go to the Google reCAPTCHA admin page.
  • Click the "+ Create button" if it is not the first site in Google reCAPTCHA. The page to register a new site will appear for the first time.
  • Fill out the form with the label for the site.
  • Choose the reCAPTCHA V2 type with "I'm not a robot" checkbox.
  • Add allowed domain names that can use this CAPTCHA.
  • Select the project, accept the terms and click the "Submit" button.
  • On the next page we will be provided with the site key and secret key. We need to copy both keys and save them for use on the website.
 

Step 2: Add Google reCAPTCHA Checkbox to HTML

The next step is to create an HTML containing a form with a Google reCAPTCHA checkbox integrated.

  • Create an HTML page with a form containing all the fields.
  • Place the reCAPTCHA container in the form where it is supposed to appear.
  • Render the reCAPTCHA field with a reCAPTCHA API script tag.
  • Add recaptcha_validate() on the form's onsubmit event. This will make the captcha field required with a simple JavaScript code.

index.html

<!DOCTYPE html>
<html>
<head>
<title>Add Google reCAPTCHA V2 to a Website - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="js/javascript.js" type="text/javascript"></script>
</head>
<body>
<section class="section py-4">
<div class="container">
<form class="captcha-form" method="POST" action="process-form.php" onsubmit="return validate_recaptcha();">
<div class="mb-4">
<label class="inline-block mb-1">Name: <span class="text-red">*</span></label>
<input type="text" name="name" class="form-control" required="required" placeholder="Enter name..." />
</div>

<!-- Google reCAPTCHA widget -->
<div class="g-recaptcha mb-4" data-sitekey="GOOGLE_RECAPTCHA_V2_SITE_KEY"></div>

<button type="submit" class="btn btn-blue btn-recaptcha-v2">
<i class="fa fa-save"></i>
Submit
</button>
</form>
</div>
</section>
</body>
</html>
 

Step 3: Make Google reCAPTCHA Field Required

Next, we add a simple JavaScript function to make the Google reCAPTCHA field required. This function is very basic and can be modified to display a proper alert box.

  • Create a validate_recaptcha() function in JavaScript.
  • Store the reCAPTCHA response token in the response variable. The grecaptcha.getResponse() returns the reCAPTCHA token if the checkbox is checked.
  • Check the response length and show an alert message if it is 0 and prevent form submission by returning false at this point.
  • Allow form submission by returning true from the function if the response length is not  0.

javascript.js

function validate_recaptcha() {
let response = grecaptcha.getResponse();

if (response.length === 0) {
alert("Please confirm you are not a bot!!!");

return false; // prevent form submission
}

return true; // allow form submission
}
 

Step 4: Validate Google reCAPTCHA in PHP

In this step we validate the user submitted reCATPCHA response before processing the form. This will mean any invalid form submission will be prevented. The validation code can be moved to a function for reuse and to avoid duplication.

  • Sanitize the $_POST array using the filter_input_array() function.
  • Check if the $post variable is not empty and contains the form data.
  • Prepare a $data array with parameters that will be sent to Google reCAPTCHA verification API.
  • Initiate a cURL object with cURL options.
  • Save the cURL response in the $response variable and close the cURL connection.
  • JSON decode the $response and store it in the $result variable.
  • If $result has a success parameter set to true/1, then verification was successful; otherwise, verification failed.
<?php
// Sanitize input array
$post = filter_input_array(INPUT_POST);

if (!empty($post)) {
    // The secret key
$secret_key = 'GOOGLE_RECAPTCHA_V2_SECRET_KEY';
$recaptcha_response = $post['g-recaptcha-response'];

// Verify the reCAPTCHA response with Google
$verify_url = 'https://www.google.com/recaptcha/api/siteverify';

$data = [
'secret' => $secret_key,
'response' => $recaptcha_response,
'remoteip' => $_SERVER['REMOTE_ADDR']
];

// Use curl to send POST request
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $verify_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

$result = json_decode($response, true);

if ($result['success']) {
// reCAPTCHA verified and we can process form
echo 'reCAPTCHA verification successful!!!';
} else {
// reCAPTCHA failed and we redirect back or handle the error other way
echo 'reCAPTCHA verification failed!!!';
}
}

We now have a Google reCAPTCHA V2 checkbox as a protection to reduce spam and bot abuse. This protection layer will help us to process only valid form submissions made by real humans.