Integrate Google reCAPTCHA in PHP with example

Manas Singh 04th Nov 2020

Google reCAPTCHA has now become one of the best solutions to prevent any kind of spam bot without any extra effort. The reCAPTCHA allows the user to make sure that he is a real human, and not any spam bot by clicking on the checkbox to validate. It is designed to protect your website from external spam or abuse.

This Google reCAPTCHA Checkbox provides an extra level of protection from any spam activities with a great user experience. We can use reCAPTCHA in any of the web forms like contact form, inquiry form, login form, etc to validate the request submitted from the users. It validates the form with a single checkbox click and stops any spam bot.

Implementation of Google reCAPTCHA with PHP

In this tutorial, we will use google reCAPTCHA v2 which is very easy to use in your web application and protects your web forms from getting spam. However, we also recommend to use Google reCAPTCHA instead of using any custom captcha code in your web forms.

Google has also released a newer version of reCAPTCHA version 3 to enhance the protection of the inquiry form and keep every leads safe without any spam entry. We will also share a separate article to integrate google reCAPTCHA v3 in PHP in our next tutorial.

As per the google announcement, Google has deprecated the Google reCAPTCHA v1.

So we advise you to update your code/script to google reCAPTCHA v2 or google reCAPTCHA v3 to get the more enhanced feature of spam protection.

In this tutorial, we will show to integrate Google reCAPTCHA v2 in PHP with step to step explanation. We will use a simple contact form to demonstrate the example, you can see the live demo or download the complete script from this article.

Also read: Google Charts or graph with PHP, Mysql and AJAX

Steps to Integrate Google reCAPTCHA v2 in PHP

We will follow the below steps to integrate Google reCAPTCHA v2 in PHP with the explanation of each step.

  • Register your website in Google reCAPTCHA Admin console.
  • Generate Site key and Secret Key
  • Create a simple contact form with reCAPTCHA
  • Validate the Google reCAPTCHA response (Server-side Validation)

Register your website in Google reCAPTCHA Admin console.

We need to register our domain on Google reCAPTCHA Admin console to access their feature. We have also created a separate and detailed article to generate the google reCAPTCHA site key and secret key.

Label: The label will help you to identify the site in the future.

reCAPTCHA type: We use reCAPTCHA v2 and select I’m not a robot Checkbox

Domains: Mention domain and related subdomain. It should not include any path, port, etc.

Google reCAPTCHA Admin console

Generate Site key and secret Key Google reCAPTCHA v2

Once we submit the above form, the domain/website is added in google reCAPTCHA and we will get the site key and secret key. These keys will use at the time of calling Google reCAPTCHA API.

Generate Site key and secret Key

Site Key: Use this key in your front end HTML code where we will show the reCAPTCHA.

Secret Key: This key is used to authorize the communication between your website and the reCAPTCHA server and validate using this key.

After generating these keys, copy the key and keep it for further use in our code.

Also read: How to generate QR Code using php

Create a simple contact form with reCAPTCHA

Now, let's create a simple contact form and use the reCAPTCHA in this form.

Here, we use one JavaScript library for reCAPTCHA API.

<script src='https://www.google.com/recaptcha/api.js'></script>

Now we use the g-recaptcha tag element to show the Google reCAPTCHA checkbox in the HTML form element

Here replace <reCAPTCHA API Site Key> with your generated API site key


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Google reCapctha Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
      <script src='https://www.google.com/recaptcha/api.js'></script>
   </head>
   <body>
      <div class="container col-sm-5">
         <h1 style="font-size: 21px; font-weight: bold;">Demo of Integrate Google recaptcha in PHP with example</h1>
         <?php if(isset($message) and $message!=""){?>
         <div class="alert alert-success"> <strong><?php echo $message;?></strong></div>
         <?php } ?>
         <form action="" method="post">
            <div class="form-group">
               <label for="pwd">Name:</label>
               <input type="text" class="form-control" id="name" placeholder="Enter your name" name="name" required>
            </div>
            <div class="form-group">
               <label for="email">Email:</label>
               <input type="email" class="form-control" id="email" placeholder="Enter your email" name="email" required>
            </div>
            <div class="form-group">
               <label for="email">Mobile:</label>
               <input type="text" class="form-control" id="mobile"  placeholder="Enter your mobile" name="mobile" required>
            </div>
            <div class="form-group">
               <label for="email">Comment:</label>
               <textarea name="comment" class="form-control" id="comment" placeholder="Enter your comment" required></textarea>
            </div>
            <div class="form-group form-check">
               <label class="form-check-label">
               <input class="form-check-input" type="checkbox" name="remember"> Remember me
               </label>
            </div>
            <div class="g-recaptcha" data-sitekey="<reCAPTCHA API Site Key>"></div>
            <input type="submit" name="submit" value="Submit" class="btn btn-primary btn-lg" style="padding: 6px 46px; margin: 16px 0 0 0;">
         </form>
      </div>
   </body>
</html>

Validate the Google reCAPTCHA response (Server-side Validation)

Now, it's time to validate the user-submitted data by the server-side script and process the request and check for any spam bot using Google reCAPTCHA.

First of all, We sanitize all the input data from users.

The value of reCAPTCHA from the front end, stores in g-recaptcha-response POST parameter to check whether the check box is checked or not.

Now we will verify the input value of reCAPTCHA using Google reCAPTCHA API in PHP.

We call the Google reCAPTCHA API and pass the Secret key and the post value (g-recaptcha-response) as a response and checks the output or response of this reCAPTCHA API.

If the response is successful, we can process the contact form and capture the data into a database or send a HTML mail to the website owner with the details.

Here replace <reCAPTCHA API Secret Key> with your generated API secret key.

<?php
  if(isset($_REQUEST['submit']) and $_REQUEST['submit']!=""){

  $user_name      = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING);
  $user_email     = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
  $mobile     = filter_var($_POST["mobile"], FILTER_SANITIZE_STRING);
  $comment   = filter_var($_POST["comment"], FILTER_SANITIZE_STRING);

  if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    // Google reCAPTCHA API secret key
    $secretKey = '<reCAPTCHA API secret Key>';
    // Verify the reCAPTCHA response
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
    // Decode json data
    $responseData = json_decode($verifyResponse);
    if($responseData->success){
     $to = "<YOUR TO MAIL ID>";
$subject = "Enquiry mail Subject";
$txt = "
<br>Name:   ". $name."
<br> Email:   ". $email."
<br> Phone:   ". $mobile."
<br> Comment:   ". $comment."
<br> Date:   ".date("d/M/y");
$email_from = "<SET YOUR FROM Mail>"; // Who the email is from
$headers = "MIME-Version: 1.0\r\n";
$headers .="Content-type: text/html;";
$headers .= " charset=iso-8859-1\r\n";
$headers .= "From: $email_from \r\n";
mail($to,$subject,$txt,$headers);
      $message = 'Data has been captured and mail has been sent';
    } else {
      $message = 'Spam bot verification failed. Please try later.';
    }
    }
    }
    ?>

Conclusion of Google reCAPTCHA

In conclusion, Google reCAPTCHA is very useful for any kind of web form to prevent spam attacks or abuse. Here, we use Google reCAPTCHA v2 in PHP with the help of a contact form for example. We have shown the Google reCAPTCHA v2 checkbox in the contact form to validate the real user.

Authored By Manas Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk