Integrate Google Invisible reCAPTCHA with PHP

The CAPTCHA functionality helps to protect web forms from being spammed. Google reCAPTCHA is a free service that allows you to implement CAPTCHA functionality in the web form. Google provides two types of reCAPTCHA for the web form, reCAPTCHA v2 and Invisible reCAPTCHA. Both kinds of reCAPTCHA integrate spam protection on the website with a better user experience. In Google reCAPTCHA v2, the user needs a single click to pass the reCAPTCHA challenge. You can easily integrate the Google reCAPTCHA checkbox with PHP in your website.

Google Invisible reCAPTCHA works the same as the reCAPTCHA checkbox, but it simplifies the CAPTCHA process. The user doesn’t need to click the checkbox to pass the reCAPTCHA challenge. Invisible reCAPTCHA validates users in the background and automatically binds the challenge to protect your HTML form against spam and automated abuse. In this tutorial, we will show you how to add Google Invisible reCAPTCHA to your web application with PHP.

To explain the Invisible reCAPTCHA implementation process, we will create an HTML contact form with Google Invisible reCAPTCHA functionality.

Generate reCAPTCHA API Keys

Before getting started, you need to register the domain of your website and generate reCAPTCHA API keys. The API keys (Site Key and Secret Key) are required to call the Google reCAPTCHA API on your website.

Register a new site:
Go to the Google reCAPTCHA Admin console and register domain.

  • Label – Make it easier for you to identify the site in the future.
  • reCAPTCHA type – Select Challenge (v2) » Invisible reCAPTCHA badge
  • Domains – Specify the domain of the website.
google-invisible-recaptcha-register-site-domain-codexworld

Accept the reCAPTCHA Terms of Service and click SUBMIT to proceed.

Get Site Key and Secret Key:
After the submission, your site will be registered with reCAPTCHA Invisible (v2), and the API keys will be generated. The Site Key and Secret Key need to be specified in the script at the time of calling the Google reCAPTCHA API.

  • Site Key – This key is used in the client-side HTML code.
  • Secret Key – This key helps to authorize communication between your site and the reCAPTCHA server and is used in the server-side script for the user’s response verification.
google-invisible-recaptcha-api-keys-site-secret-codexworld

Copy the Site Key and Secret Key for later use in the Google reCAPTCHA v2 API integration code.

Add Invisible reCAPTCHA Badge to HTML Form

JavaScript Code:
First, include the reCAPTCHA JavaScript API library and set the onload callback function.

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback" async defer></script>

Define a JavaScript method to use as a callback function:

  • onloadCallback – Specify the onload callback function and call grecaptcha.execute() method. It programmatically invokes the reCAPTCHA check.
<script>
var onloadCallback = function() {
    grecaptcha.execute();
};
</script>

HTML Code:
Create an HTML element (div) with a data-size="invisible" attribute, so that the CAPTCHA challenge can be attached.

  • Use the class="g-recaptcha" attribute to make the div available with Google reCAPTCHA.
  • The reCAPTCHA API Site Key must be specified in the data-sitekey attribute.
<form method="POST" action="submit.php">
    <div class="form-item">
        <label>Full Name</label>
        <input type="text" name="name" value="" required>
    </div>
    <div class="form-item">
        <label>E-Mail</label>
        <input type="email" name="email" value="" required>
    </div>
    <div class="form-item">
        <label>Message</label>
        <textarea name="message" rows="4" required></textarea>
    </div>

    <div class="form-item">
        <!-- Google reCAPTCHA widget -->
        <div class="g-recaptcha"
            data-sitekey="_YOUR_reCAPTCHA_SITE_KEY_"
            data-size="invisible">
        </div>
    </div>

    <!-- Submit button -->
    <input type="submit" name="submit" value="Send Message">
</form>

Verify reCAPTCHA API Response (Server-side Validation)

After the form submission, you need to verify the user’s response to prevent spam submissions. In the submit.php file, the CAPTCHA response is verified with Google Invisible reCAPTCHA API using PHP.

  • Validate form fields to check whether the user fills the input fields.
  • Use the g-recaptcha-response POST parameter to verify the reCAPTCHA challenge.
    • Call the Google reCAPTCHA API and pass the Site Secret Key (secret) & user’s response (response).
  • If the reCAPTCHA response is valid and successful,
    • The contact request will process further and an email will be sent to the site admin with the contact form data using PHP.
  • Render the status message.
<?php 
// Google reCAPTCHA API keys settings
$API_SECRET_KEY '_YOUR_reCAPTCHA_SECRET_KEY_';

// Email settings
$RECIPIENT_EMAIL 'admin@example.com';


// If the form is submitted
$postData $statusMsg '';
$status 'error';
if(isset(
$_POST['submit'])){
    
$postData $_POST;
    
    
// Validate form input fields
    
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])){
        
        
// Validate reCAPTCHA submission
        
if(!empty($_POST['g-recaptcha-response'])){

            
// Verify the reCAPTCHA API response
            
$verifyResponse file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$API_SECRET_KEY.'&response='.$_POST['g-recaptcha-response']);
            
            
// Decode JSON data of API response
            
$responseData json_decode($verifyResponse);
            
            
// If the reCAPTCHA API response is valid
            
if($responseData->success){
                
// Retrieve value from the form input fields
                
$name = !empty($_POST['name'])?$_POST['name']:'';
                
$email = !empty($_POST['email'])?$_POST['email']:'';
                
$message = !empty($_POST['message'])?$_POST['message']:'';
                
                
// Send email notification to the site admin
                
$subject 'New Contact Request Submitted';
                
$htmlContent "
                    <h4>Contact request details</h4>
                    <p><b>Name: </b>"
.$name."</p>
                    <p><b>Email: </b>"
.$email."</p>
                    <p><b>Message: </b>"
.$message."</p>
                "
;
                
                
// Always set content-type when sending HTML email
                
$headers "MIME-Version: 1.0" "\r\n";
                
$headers .= "Content-type:text/html;charset=UTF-8" "\r\n";
                
// More headers
                
$headers .= 'From:'.$name.' <'.$email.'>' "\r\n";
                
                
// Send email
                
@mail($RECIPIENT_EMAIL$subject$htmlContent$headers);
                
                
$status 'success';
                
$statusMsg 'Thank you! Your contact request has been submitted successfully.';
                
$postData '';
            }else{
                
$statusMsg 'Robot verification failed, please try again.';
            }
        }else{
            
$statusMsg 'Robot verification failed, please try again.';
        }
    }else{
        
$statusMsg 'Please fill all the mandatory fields.';
    }
}

echo 
$statusMsg;
?>

Integrate Google reCAPTCHA in Modal Popup Form

Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request

1 Comment

  1. Kay Said...

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up