How to Integrate Google reCAPTCHA in PHP 7 Contact Form

Last updated on by Digamber
Google reCAPTCHA is the best solution to protect web forms from spam. The reCAPTCHA is a powerful spam protection tool that makes sure you are a real human, and Google reCaptcha checkbox also provides the best user experience in a few lines of codes.

Integrate Google reCAPTCHA in PHP Contact Form

LIVE DEMO

Google has released reCAPTCHA version 3 recently, and version 2 was also there to protect against bad bots. To enhance the productivity of Contact forms, we must implement the reCAPTCHA code in our sites. It validates the contact form with a single tick, and it stops bots from sending spam mails.

Implementing Google reCaptcha code in PHP contact form is very much useful from the UX perspective. This tool specially designed for checking genuine human users against the bad bots. A user has to click on a checkbox to confirm his identity. Simple, Isn’t It.

Usually, Google reCAPTCHA is used to protect from bots; however, you can also validate any response generated from your web app with reCAPTHA. We have published the previous tutorial on creating a custom CAPTCHA with PHP.

Google reCAPTCHA integration process:

  • Generate reCAPTCHA Site & Security API Keys.
  • Create an HTML form with Bootstrap.
  • Integrate reCAPTCHA in a PHP form.
  • Validate the response with Google reCAPTCHA.
  • Send email to post form data in PHP.

Generate reCAPTCHA Site & Security API Keys

We must have Google reCaptcha Site and Secret Key, and it requires you to register your domain that needs to be protected against spam.

Visit the reCAPTCHA website and register your application.

Enter the Label name. It helps you recognize your registered domain name.

We can see reCAPTCHA version 3 and 2, select reCAPTCHA v2 > I’m not a robot option by selecting the radio button.

Enter your domain name, that requires protection from bots.

Register a new site for Google reCAPTCHA

Click on the “Save” button, you will be redirected to a new page.

Get Google reCaptcha Site and Secret Key

Copy your reCAPTCHA Site Key and Secret Key, we will need these API keys in a next step.

Integrate Google reCAPTCHA in PHP Contact Form

To add the Google reCAPTCHA Widget in HTML Form, we require to place the reCAPTCHA JavaScript file at the bottom of the web page. Just paste the following link before the body tag closes.

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

Next, include the g-recaptcha HTML tag inside the HTML Form element, place it exactly where you would like to show the reCAPTHCA tool.

The g-recaptcha widget comes with the data-site key attribute. We need to paste the site key that we generated in the previous step.

<div class="g-recaptcha" data-sitekey="Your_Site_Key"></div>

Specify the name property in input fields that interacts with the PHP API, Define the alert box to display success and error messages.

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>PHP Contact Form with Captcha</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/css/style.css">
</head>

<body>

  <div class="container mt-5">
    
    <h2>Implement Google reCAPTCHA in PHP Contact Form</h2>

    <?php include('scripts/form.php'); ?>

    <!-- Error messages -->
    <?php if(!empty($response)) {?>
    <div class="form-group col-12 text-center">
      <div class="alert text-center <?php echo $response['status']; ?>">
        <?php echo $response['message']; ?>
      </div>
    </div>
    <?php }?>

    <!-- Contact form -->
    <form action="" name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" novalidate>
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" id="name">
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" id="email">
      </div>

      <div class="form-group">
        <label>Subject</label>
        <input type="text" class="form-control" name="subject" id="subject">
      </div>

      <div class="form-group">
        <label>Message</label>
        <textarea class="form-control" rows="4" name="message" id="message"></textarea>
      </div>

      <div class="form-group">
        <!-- Google reCAPTCHA block -->
        <div class="g-recaptcha" data-sitekey="6LfZ4AAVAAAAAFP6tyNYWgycDvXHIfjZg9shDZ05"></div>
      </div>

      <div class="form-group">
        <input type="submit" name="send" value="Send" class="btn btn-dark btn-block">        
      </div>
    </form>
  </div>

  <!-- Google reCaptcha -->
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</body>

</html>

Google reCAPTCHA Validation Before Form Submit in PHP

Form field validation makes sure if the user has entered the required values or not. Google reCAPTCHA response is triggered based on the PHP post request. The API call validates the token and returns the JSON response through the reCAPTCHA API and Secret key.

A user checks the reCAPTCHA checkbox to complete the reCaptcha challenge. If the reCAPTCHA response is successful form will be submitted, and the message will be displayed to the user.

<?php
    if(isset($_POST["send"])) {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $subject = $_POST["subject"];
        $message = $_POST["message"];
        
        // Form validation
        if(!empty($name) && !empty($email) && !empty($subject) && !empty($message)){

            // reCAPTCHA validation
            if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {

                // Google secret API
                $secretAPIkey = '6LfZ4AAVAAAAAF722GPGWyJ_lf1F2hMSWzPHmuYc';

                // reCAPTCHA response verification
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$_POST['g-recaptcha-response']);

                // Decode JSON data
                $response = json_decode($verifyResponse);
                    if($response->success){

                        $toMail = "johndoe@gmail.com";
                        $header = "From: " . $name . "<". $email .">\r\n";
                        mail($toMail, $subject, $message, $header);

                        $response = array(
                            "status" => "alert-success",
                            "message" => "Your mail have been sent."
                        );
                    } else {
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Robot verification failed, please try again."
                        );
                    }       
            } else{ 
                $response = array(
                    "status" => "alert-danger",
                    "message" => "Plese check on the reCAPTCHA box."
                );
            } 
        }  else{ 
            $response = array(
                "status" => "alert-danger",
                "message" => "All the fields are required."
            );
        }
    }  
?>

Google reCAPTCHA in PHP Contact Form Example

Here is the screenshot that describes the Google reCAPTCHA checkbox widget that we added in the PHP contact form.

Google reCAPTCHA in PHP Contact Form Example

Conclusion

We have completed the PHP Google reCAPTCHA tutorial. We have learned how to integrate Google reCAPTCHA in PHP Form easily. Also, learn to implement server-side validation to Google reCAPTCHA version 2. You can also check out the CAPTCHA analytics to figure out the request flow.

Get the complete code of this tutorial on GitHub.