Integrate the Google reCAPTCHA in PHP Contact Form

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenge-response test used in computing to determine whether or not the user is human. In this tutorial, we have shared how to integrate the Google reCAPTCHA in PHP contact form.
Google reCaptcha helps you create a shield that protects your web application from spam and bots. This is a PHP library that wraps up the server-side verification step required to process responses from the reCAPTCHA service. This is a very simple script, you can copy-paste and modify it according to your requirement.
Downlod Google reCAPTCHA code library click here.
Register the domain of your website at Google reCAPTCHA Admin console.
  • Label – choose label name.
  • reCAPTCHA type – Select reCAPTCHA v2 >> I’m not a robot Checkbox
  • Domains – Specify the domain of your website.
Get Site Key and Secret Key:
  • 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.
Before started to implement the PHP Contact Form with Google reCAPTCHA, look files structure:
  • php-contact-form-with-google-recaptcha
    • css
      • style.css
    • library
      • src
        • autoload.php
    • config.php
    • index.php
    • contact.php
include reCAPTCHA Widget to HTML Form
Add tag g-recaptcha tag element in the HTML form where you want to display the reCAPTCHA 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.
Step 1: Create config.php
Step 2: Create HTML Form
Step 3: Ajax code with with custom validation (include index.php)
>
Step 4: Verify reCAPTCHA Response (using Server-side Validation)
This library comes in when you need to verify the user’s response. On the PHP side you need the response from the reCAPTCHA service and secret key from your credentials. Instantiate the ReCaptcha class with your secret key, specify any additional validation rules, and then call verify() with the reCAPTCHA response and user’s IP address.
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
footer.php