How to Enable and Customize Google Invisible reCAPTCHA in a Webpage

by Vincy. Last modified on July 3rd, 2022.

We have seen several examples of adding captcha in a PHP web application. CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart”. The acronym itself stands for the importance of implementing captcha in an application.

Google reCaptcha is the leading captcha service that provides never-beatable results in differentiating humans and robots.

In this tutorial, we are going to see how to integrate and customize Google’s invisible ReCaptcha using PHP. In a previous tutorial, we have seen how to enable Google reCaptcha by using an automatic rendering method.

The example code below uses PHP cURL script to access the Google reCaptcha API for validation.

There are three ways of enabling Google’s Invisible ReCaptcha. Those are,

  1. Automatically bind the reCaptcha challenge to a button element.
  2. Programmatically bind the challenge to a button element.
  3. Programmatically invoke the challenge.

how-to-enable-and-customize-google-invisible-recaptcha-in-a-webpage-output

Read more about Google invisible reCaptcha by reading their official documentation.

In this example, I have used the third method for invoking Google’s invisible reCaptcha service. On page load, Google’s invisible recaptcha is invoked and rendered in a DIV on an HTML form. While rendering, the callback function will be called by sending the response token. This token will be validated in the PHP code to check whether it is set or not.

HTML Form to Render Google Invisible reCaptcha

This is the code to display the HTML form with two input fields username and email address. On loading this HTML page the Google invisible reCaptcha is called and rendered in a DIV. This DIV must have the required HTML5 data attribute with the Google reCaptcha key to render the invisible captcha. This form contains a hidden input field to set the response token on successful execution.

<form action="process.php" method="post" onsubmit="return validateContact();">
        <div class="form-row">
            <div class="name">
                <label>Name:</label> 
                <input type="text" name="name" id="name">
                <span id="userName-info" class="info"></span>
            </div><br>
            <div class="email">
                <label>Email:</label> 
                <input type="email" name="email" id="email">
                <span id="userEmail-info" class="info"></span>
            </div><br>
            <!-- Google reCAPTCHA widget -->
            <div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY" data-badge="inline" data-size="invisible" data-callback="setResponse"></div><br>
            <input type="hidden" id="captcha-response" name="captcha-response" />
        </div>
    
        <div class="button-row">
            <input type="submit" name="submit" value="SUBMIT" >
        </div>   
</form>

On submitting this form, the validateContact() JavaScript method will be executed to check the form field values are not empty. We have seen a variety of example code for client-side validation. For example, the simple PHP contact form example with JavaScript validation code.  This validation will return a boolean value to proceed with the form submit to the PHP code.

function validateContact() {
	var valid = true;
        $(".info").html('');
	if(!$("#name").val()) {
		$("#userName-info").html("(required)");
                 $("#name").css('border-color','red');
		valid = false;
	}
	if(!$("#email").val()) {
		$("#userEmail-info").html("(required)");
                 $("#email").css('border-color','red');
		valid = false;
	}
	if(!$("#email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
		$("#userEmail-info").html("(invalid)");
                 $("#email").css('border-color','red');
		valid = false;
	}
	return valid;
}

Invoking Google Invisible reCaptcha Programmatically

This code shows how to invoke Google invisible reCaptcha by setting the “onload” callback. On the landing page, we call the Google reCaptcha API by setting the function name to be called on page load. In this function, the Google reCaptcha is invoked to render the reCaptcha widget in a DIV element. As we have seen before, the DIV element contains the data attributes data-size=“invisible”, data-callback=“setResponse”. The data callback is an optional parameter.

The setResponse() callback is invoked while rending the Google invisible reCaptcha widget. The response token passed as the parameter of this callback will be set to a hidden input and validated in the PHP code.

PHP Code to verify the response

In this PHP code, the Google reCaptcha site verification request is set via the PHP CURL request. Based on the server verification result, the response text is created to acknowledge the user.

<?php
if(isset($_POST['submit'])){
    if(isset($_POST['captcha-response']) && !empty($_POST['captcha-response'])){       
        $data = array(
            'secret' => "YOUR-SECRET-KEY",
            'response' => $_POST['captcha-response']
        );        
        $verify = curl_init();
        curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($verify, CURLOPT_POST, true);
        curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($verify);       
        if($response == true){ 
            $result='<div class="success">Your request has been successfully received</div>';
            echo $result;
        }else{
            $result='<div class="error">Verification failed, please try again</div>';
            echo $result;
        }
    }else{
        $result='<div class="error">Verification failed, please try again</div>';
        echo $result;
    }
}
?>

Download

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page