Add Google reCAPTCHA V2 to Website

To protect websites against spam bots google provides a free reCAPTCHA service that can be integrated to a website in form of a checkbox. Learn how to add google reCAPTCHA V2 to website step by step.

Add Google reCAPTCHA V2 to Website

Spam bots can be a headache to website developers and owners causing overwhelmed database entries and wasting server resources. To counter this issue it is necessary to protect forms with google reCAPTCHA V2 which helps to protect a website from spam and abuse. In this post we will walk through steps to integrate reCAPTCHA V2 of google in simple steps.

 

How to Add Google reCAPTCHA V2 to Website

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

 

Step 1: Register Website on Google reCAPTCHA

First step is to get site key and site secret from google reCAPTCHA admin to use in our website. Steps to register a website on google reCAPTCHA are:

  • Go to google reCAPTCHA admin page.
  • Click the "+ Create button" if it is not first site in google reCAPTCHA. The register new site page will appear for first time registration.
  • Fill out the form with label for site.
  • Choose reCAPTCHA V2 type with "I'm not a robot" checkbox.
  • Add allowed domains name that can use this CAPTCHA.
  • Select the project, accept terms and click "Submit" button.
  • The next page will show site key and secret key. Copy both keys and save them for use in website. 
 

Step 2: Add Google reCAPTCHA Checkbox to HTML

Next step is to create an HTML containing a form with google reCAPTCHA checkbox integrated.

  • Create an HTML page with a form containing with all the fields.
  • Place the google reCAPCTHA V2 container in form where it should appear.
  • Add the reCAPTCHA API script tag to render the reCAPTCHA field.
  • Add recaptcha_validate() on form 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 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" />

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript" src="js/javascript.js"></script>
<link rel="stylesheet" href="css/style.css" />
</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 which can be modified to display a proper alert box.

  • Create a validate_recaptcha() function in javascript.
  • Store reCAPTCHA response token in response variable. The grecaptcha.getResponse() returns the reCAPTCHA token if checkbox is checked.
  • Check if response length is 0 then alert a message and prevent form submission by returning false at this point.
  • Otherwise allow form for submission by returning true from function.

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 reCAPTCHA V2 in PHP

Next step is to process the submitted form on server side and validate submitted google reCAPTCHA response. The verification code in this snippet can be moved to a function for re-use and avoid duplication.

  • Sanitize the $_POST array using filter_input_array() function.
  • Check if $post variable is not empty and contains the form data.
  • Prepare a $data array with parameters to send to google reCAPTCHA verification API endpoint.
  • Initiate a cURL request and set basic cURL options.
  • Save the cURL response in $response variable and close the cURL connection.
  • JSON decode the $response and store it in $result variable.
  • If $result has success parameter set to true/1 then verification was successful otherwise verification failed
<?php
// Sanitize input array
$post = filter_input_array(INPUT_POST, [
'name' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
'g-recaptcha-response' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
]);

if(!empty($post)){
// Your 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 – process form
echo 'reCAPTCHA verification successful!!!';
} else {
// reCAPTCHA failed, redirect back or handle error as needed
echo 'reCAPTCHA verification failed!!!';
}
}

We demonstrated how to add google reCAPTCHA V2 checkbox to a website. Adding google reCAPTCHA to website can reduce spam and bot abuse. This google reCAPTCHA V2 example can be modified as per application's requirement.