Integrate Google reCAPTCHA Checkbox with PHP

Google has released the new reCAPTCHA v2 checkbox widget. Using the reCAPTCHA widget users can prove that they are human without solving a CAPTCHA question. Only a single click is needed to confirm they are not a robot. The Google reCAPTCHA Checkbox protects your website from spam with a better user experience. Generally, Google reCAPTCHA functionality is used in the web form to protect from spam. In addition, the Google reCAPTCHA can also be used to protect websites from spam requests. The reCAPTCHA helps to validate any response coming from the website that is useful for bot protection.

Google reCAPTCHA API provides an easy and effective way to protect your web form or web page from getting spam. Google reCAPTCHA can be easily integrated into the website using PHP. In this tutorial, we will show you how to integrate Google reCAPTCHA checkbox with PHP in the web form.

In the example code, the following functionality will be implemented to demonstrate the Google reCAPTCHA integration with PHP.

  • Create an HTML form to submit contact request.
  • Add a reCAPTCHA checkbox widget to the form.
  • Verifying the response with Google reCAPTCHA API.
  • Retrieve form data and send email using PHP.
google-recaptcha-demo-by-codexworld

Generate reCAPTCHA API Keys

The reCAPTCHA keys are required to call the Google reCAPTCHA API. Before adding the reCAPTCHA v2 checkbox to your site, you need to register your site and get reCAPTCHA API keys.

Register Website:
Register the domain of your website at Google reCAPTCHA Admin console.

  • Label – It helps to identify your registered site in the future.
  • reCAPTCHA type – Select reCAPTCHA v2 » I’m not a robot Checkbox
  • Domains – Specify the domain of your website.
google-recaptcha-v2-checkbox-add-site-domain-codexworld

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

  • Site Key – This key is used in the HTML code of the reCAPTCHA widget.
  • Secret Key – This key helps to authorize communication between your site and the reCAPTCHA server.
google-recaptcha-v2-checkbox-create-site-key-secret-codexworld

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

Add reCAPTCHA Widget to HTML Form

First, include the JavaScript library of reCAPTCHA API.

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

Add the g-recaptcha tag element in the HTML form where you want to display the reCAPTCHA checkbox widget.

  • The g-recaptcha DIV element has a class (named “g-recaptcha”) and data-sitekey attributes.
  • The Site Key of the reCAPTCHA API will be specified in the data-sitekey attribute.
<form action="" method="post">
    <div class="input-group">
        <input type="text" name="name" value="" placeholder="Your name" required="" />
    </div>
    <div class="input-group">	
        <input type="email" name="email" value="" placeholder="Your email" required="" />
    </div>
    <div class="input-group">
        <textarea name="message" placeholder="Type message..." required="" ></textarea>
    </div>
		
    <!-- Google reCAPTCHA box -->
    <div class="g-recaptcha" data-sitekey="Your_reCAPTCHA_Site_Key"></div>
	
    <!-- Submit button -->
    <input type="submit" name="submit" value="SUBMIT">
</form>

Verify reCAPTCHA API Response (Server-side Validation)

After the form submission, the input data will be submitted to the server-side script to verify the user’s response and process the contact request.

  • Validate form fields to check whether the user fills the input fields.
  • Use the g-recaptcha-response POST parameter to check whether the user selects reCAPTCHA checkbox.
  • Verify the reCAPTCHA challenge using reCAPTCHA API and PHP.
    • Call the Google reCAPTCHA API and pass the Site Secret Key (secret) & user’s response (response). Check the reCAPTCHA API 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.
    • The status message is shown to the user.
<?php 

// Google reCAPTCHA API keys settings
$secretKey  'Your_reCaptcha_Secret_Key';

// Email settings
$recipientEmail '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 checkbox
        
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){

            
// Verify the reCAPTCHA API response
            
$verifyResponse file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&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
                
$to $recipientEmail;
                
$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($to$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 'Please check the reCAPTCHA checkbox.';
        }
    }else{
        
$statusMsg 'Please fill all the mandatory fields.';
    }
}

?>

Use the following code to display the form submission status message in the HTML form section.

<?php if(!empty($statusMsg)){ ?>
    <p class="status-msg <?php echo $status?>"><?php echo $statusMsg?></p>
<?php ?>

Google Invisible reCAPTCHA with PHP

Conclusion

There are multiple options are available to add CAPTCHA functionality to the website. The Google reCAPTCHA is the easiest option to add a CAPTCHA challenge to the form on the website. You can also, see the analytics reports of the CAPTCHA Requests in the reCAPTCHA admin panel. In the example code, we have shown how you can add Google reCAPTCHA checkbox in the contact form. Not only the contact form but also you can use our code to integrate Google reCAPTCHA into any type of form in the web application.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

51 Comments

  1. Lucian Said...
    • CodexWorld Said...
  2. Jeremy Said...

Leave a reply

keyboard_double_arrow_up