How to Enable and Customize Google Invisible reCAPTCHA in a Webpage

Last modified on September 22nd, 2018 by Vincy.

We have seen several examples for 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.

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

Google reCaptcha is the leading captcha service that provides never beatable result 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 automatic rendering method.

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.

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, the 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 fields values are not empty. We have seen a varity 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 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. In 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;
    }
}
?>

Google Invisible reCAPTCHA with PHP Output

This screenshot shows the output screen of the HTML form where the Google invisible reCaptcha widget is rendered. The message displayed above the form is the success message. This will be responded on success reCaptcha token verification in the server side PHP code.

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

Download

This PHP code tutorial was published on September 3, 2018.

↑ Back to Top

Share this Article