Guide: Custom Integration of Google reCAPTCHA v2 with Drupal 7

Indraraj Weerawansa
5 min readMar 12, 2024
Photo by FlyD on Unsplash

Google reCAPTCHA is a powerful tool used by website owners to protect against spam and abuse. In Drupal 7, integrating Google reCAPTCHA v2 can enhance the security of your website forms. This guide will walk you through the process of integrating Google reCAPTCHA v2 manually (without using existing modules) into your Drupal 7 website step-by-step.

When using existing modules for Google Captcha, some may only allow use within Drupal’s standard/default forms (such as user registration, login, etc.). Others may be challenging to implement within customized forms, with limited options for error handling and customization. In this article, I’ll demonstrate a straightforward method to integrate reCAPTCHA v2, allowing for customization according to your preferences.

Throughout this article, I use the Drupal 7 home folder name as ‘my_website’.

Step 1: Sign Up for Google reCAPTCHA

Before you can integrate Google reCAPTCHA, you need to sign up for an account on the reCAPTCHA website

https://developers.google.com/recaptcha/intro

In here you need to select Checkbox option in reCAPTCHA v2.

Once you sign up, you will receive site keys and secret keys that you will need during the integration process.

Step 2: Store the reCAPTCHA keys in your code

When you receive Google reCAPTCHA Keys, the next step is to store them securely. To do this, you can add it to the settings.php file as follows.

File path - my_website/sites/default/settings.php

$conf['reCAPTCHA_site_key'] = 'YOUR SITE KEY';
$conf['reCAPTCHA_secret_key'] = 'YOUR SECRET KEY';

Now you can get those keys anywhere in the Drupal 7 site using the function “variable_get()”.

$secret_key = variable_get(‘reCAPTCHA_secret_key’, ‘’);

Step 3: Add reCAPTCHA to the front end and validation

In this step, we will integrate reCAPTCHA into the front end of the page and combine it with basic jQuery form validation. Here’s how to do it:

First, load the site key using PHP:

$reCAPTCHA_site_key = variable_get(‘reCAPTCHA_site_key’, ‘’);

Then, you need to load the jQuery and jQuery validation libraries:

<script src= “https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> 
<script src= “https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"> </script>

Next, load the JavaScript API using the following line in the HTML head section:

<script src=”https://www.google.com/recaptcha/api.js"></script>

Now, you can create the form as shown below:

<?php
$reCAPTCHA_site_key = variable_get('reCAPTCHA_site_key', '');
?>
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'> </script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js'> </script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form id='captcha_form' name='captcha_form' method='POST' action='form/submit-form'>
<input name='first_name' id='first_name' type='text'>
<label for='first_name'>First Name *</label>
<input name='last_name' id='last_name' type='text'>
<label for='last_name'>Last Name *</label>
<div class='g-recaptcha' data-sitekey='<?php echo $reCAPTCHA_site_key; ?>'></div>
<br />
<span class='recaptcha-message'></span>
<button id='captcha_submit' type='submit' value='Submit' name='submit'>Submit</button>
</form>
</body>
</html>

Step 4: Add captcha to jQuery form validation

To do this we need to add a captcha check box click as required. Otherwise, if the user forgets to click the captcha checkbox in the form submission backend captcha validation will be failed.

Here is the sample javascript code to validate captcha:

<script>
$('#captcha_submit').validate({
rules: {
first_name: 'required',
last_name: 'required'
},
messages: {
first_name: 'Please enter the first name',
last_name: 'Please enter the last name'
},
submitHandler: function(form) {
if (grecaptcha.getResponse() == '') {
$('.g-recaptcha').css('border', 'solid 1px red');
$('.recaptcha-message').html('Please verify captcha');
setTimeout(function() {
$('.g-recaptcha').css('border', 'none');
$('.recaptcha-message').html('');
}, 5000);
return false;
}
return true;
}
});
</script>

Step 5: Create the backend reCAPTCHA v3 validation

For this purpose, I have created a captcha validation function inside a module (my_module.module), allowing us to use that function site-wide for all custom forms.

I have created a module named ‘my_module.module’ and created a function named ‘google_recaptcha_validation’.

Module path - my_website/sites/all/modules/my_module/my_module.module

Here’s an example code snippet that demonstrates how to verify the reCAPTCHA response in PHP:

function google_recaptcha_validation($form_name, $post_data)
{
$validated = false;
try {
if (isset($post_data['g-recaptcha-response'])) {
// Your secret key
$secret = variable_get('reCAPTCHA_secret_key', '');

// Verify the user's response
$captcha = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];

$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
);

$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$responseJson = json_decode($result);

if ($responseJson->success == true) {
$validated = true;
} else {
watchdog('recaptcha', 'Fail to validate captch | Captcha responce - %response | Body = %body | Form Name = %form_name', array('%response' => $result, '%body' => json_encode($post_data), '%form_name' => $form_name), WATCHDOG_ERROR);
}
} else {
watchdog('recaptcha', 'Empty Captcha responce | Body = %body | Form Name = %form_name', array('%body' => json_encode($post_data), '%form_name' => $form_name), WATCHDOG_ERROR);
}
} catch (Exception $ex) {
watchdog('recaptcha', 'Re-captcha exception responce | Body = %body | Form Name = %form_name | error = %error', array('%body' => json_encode($post_data), '%form_name' => $form_name, '%error' => $ex->getMessage()), WATCHDOG_ERROR);
}
return $validated;
}

Step 6: Use the reCAPTCHA validation in form submission

Finally, in the form submits section, you need to create a page in Drupal 7 with the URL alias ‘form/submit-form’.

On that page, you can add the following sample code segment to validate the captcha response from form submission:

if (!empty($_POST)) {
$captcha = google_recaptcha_validation('SampleCaptchaForm', $_POST);
if ($captcha) {
//Form submission logic goes here
echo 'Captcha success';
} else {
//do something as failing action here
echo 'Captcha faild';
}
}

Thats all for Google reCAPTCHA v2 custom integration with D7!

You can find all the code examples mentioned in this article in my GitHub repository:

https://github.com/indrarajw/Custom-Integration-of-Google-reCAPTCHA-v2-with-Drupal-7

Here are few points to consider at the end…

In this article, step 6 uses the “file_get_contents()” function to maintain code simplicity. However, for enhanced control and error handling, you can use cURL to validate the captcha response against Google.
To implement cURL for captcha validation, you would replace the file_get_contents() function with cURL functions such as curl_init(), curl_setopt(), curl_exec(), and curl_close(). These functions enable you to customize the request, set headers, handle errors, and process the response in a more controlled manner.

Sometimes reCAPTCHA v2 can become frustrating for end users due to its behavior of frequently presenting puzzles or challenges. This can happen when the reCAPTCHA system detects unusual or suspicious activity, such as multiple failed login attempts or rapid form submissions.

This frequent appearance of puzzles can disrupt the user experience, especially if users need to repeatedly solve puzzles to access content or complete tasks. This can lead to frustration and annoyance for users, potentially impacting their perception of the website’s usability.

So it is important to maintain a balance between security measures and user experience when implementing any system. One solution to relieve this frustration is to consider implementing reCAPTCHA v3. Unlike v2, reCAPTCHA v3 operates silently in the background, assessing user behavior and assigning a score to determine the probability of a user being a bot. In the next post, I’ll explain the integration process of reCAPTCHA v3 with Drupal 7 custom forms in detail.

--

--

Indraraj Weerawansa

Web Development | Web Security | PHP | Drupal | System Integration & Automation