Add Google reCAPTCHA V2 to a Website (Prevent Spam Form Submissions)

Google offers a free reCAPTCHA service that helps websites fight against spam bots. This service is integrated into a website as a checkbox to confirm human interaction with the page. Learn how to add it to websites to block automated bots and increase website security.

Add Google reCAPTCHA V2 to a Website

Spam bots are designed to automatically create a large number of unwanted content like a post, comment, or create a fake account. One common approach to counter this spam issue is to protect website forms with some kind of human verification service like Cloudflare Turnstile, Google reCAPTCHA V3, hCAPTCHA, or any other similar service. This post demonstrates how to add Google's reCAPTCHA v2 to a website.

 

How to Add Google reCAPTCHA V2 to a Website?

This service can be easily integrated into a website by following a few simple steps. These steps involve registering a website on Google reCAPTCHA, retrieving the site key and secret key, integrating it into the website, and validating the CAPTCHA on the server side.

 

Step 1: Register the Website on Google reCAPTCHA

The first step is to add our website to Google's reCAPTCHA console and get the site key and site secret for the integration. The following are the steps to do it:

  • Go to the Google reCAPTCHA admin page.
  • Click the "+ Create button" if it is not the first site to add. 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 the "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.
 

Step 2: Add Google reCAPTCHA Checkbox in HTML

Once we have our site key and secret, we can add the reCAPTCHA to our website forms. We create an HTML page containing a form and a container for the reCAPTCHA.

  • 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() to the form's onsubmit event to make the captcha field required with JavaScript.

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

We want to make sure the user is not able to submit the form until the reCAPTCHA checkbox is checked. We can make it a required field with the following simple function, which 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

When the form is submitted along with the reCAPTCHA response, we need to verify it in a server-side script before processing the form. The server-side script uses PHP's cURL extension to make a request to Google's reCAPTCHA verification API for verification. 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 the 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.
  • The true/1 value of the $result variable will mean verification was successful.

process-form.php

<?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 verification successful - process the form
echo 'reCAPTCHA verification successful!';
} else {
// reCAPTCHA verification failed - redirect back or handle the error another way
echo 'reCAPTCHA verification failed!';
}
}

Google reCAPTCHA is a free yet useful service that enables websites to differentiate between human form submissions and automated form submissions. We demonstrated how to add a "I'm not a robot" checkbox to a website using Google reCAPTCHA v2 as a protection layer against spam form submissions.