PHP - Implement Google reCAPTCHA v2 Tutorial with Example

Sovary May 31, 2022 916
5 minutes read

This article will demonstration how to implement Google reCaptcha v2 with PHP. We will start from scratch with example Google reCaptcha v2 with check box to validation and prevent spam submissions. Using Google reCAPTCHA users can prove that they are not robot without solving complex CAPTCHA question.

Google reCAPTCHA provide API to protect your submit request web from spam submition, following step below will show you how easily integrated Google reCaptcha into website using PHP with sample web form.

The steps to do:

  • Register Website and reCAPTCHA v2 API Keys
  • Create Sample HTML with Submit Request
  • Add reCaptcha to Form
  • Verify reCaptcha on Server

Register to Gernerate reCAPTCHA API Keys

Using Google reCaptcha service you need to register your website on Google reCAPTCHA. You have to log in to google account then create app by filling the form.

There are two options in reCHAPTCHA type, select reCHAPTCHA v2 and choose "I am not robot" checkbox. See image below

register google recaptcha v2

After click submit button you will see another panel which contain confidential information site key, secret key. Those keys will place on client and server side to validate at the time calling reCHAPTCHA API.

  • Site Key - key insert in HTML code for client side (Public Key)
  • Secret Key - key for validate between your site and the reCAPTCHA server (Private Key).

We will use these keys later. See image below

register google recaptcha v2 client keys and server key

Create HTML Submit Form

Example we have a form for user to comment on your blog and have structure as below

<html>
  <head>
    <title>Google reCAPTHA v2</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
        <h1>Google reCAPTHA v2 CamboTutorial</h1>
        <form action="submit.php" method="POST">
            <div class="mb-3">
                <label class="form-label">Email address</label>
                <input type="email" name="email" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">Comment:</label>
                <textarea class="form-control" name="comment"></textarea>
            </div>
            <div class="mb-3">
                <button type="submit" class="btn btn-primary">Post</button>
            </div>
        </form>
    </div>
  </body>
</html>

Insert reCaptcha in HTML (Client Side)

Add reCAPTCHA CDN Javascript API in your web page and insert reCAPTCHA element where you want to display.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="[your_site_key]"></div> 

Replace [your_site_key] with your API Site key. HTML Form should structure as below

index.php

<html>
  <head>
    <title>Google reCAPTHA v2</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src='https://www.google.com/recaptcha/api.js' async defer></script>
  </head>
  <body>
    <div class="container">
        <h1>Google reCAPTHA v2 CamboTutorial</h1>
        <form action="submit.php" method="POST">
            <div class="mb-3">
                <label class="form-label">Email address</label>
                <input type="email" name="email" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">Comment:</label>
                <textarea class="form-control" name="comment"></textarea>
            </div>
            <!--Checkbox reCAPTCHA-->
            <div class="mb-3">
                <div class="g-recaptcha" data-sitekey="[your_site_key]"></div>
            </div>
            <div class="mb-3">
                <button type="submit" class="btn btn-primary">Post</button>
            </div>
        </form>
    </div>
  </body>
</html>

Verify Submit Form with reCAPTCHA (Server Side)

In web application to communicate between server and client we have to know the paramenters were sent and the verb methods (POST, GET, PUT, DELETE). 

Use g-recaptcha-response with POST parameter to capture if user select reCAPTCHA check box. Make reCAPTCHA API request to https://www.google.com/recaptcha/api/siteverify with POST method and see the parameters below

Parameter Type Description
secret String (Required)  API Key which you register in Google reCAPTCHA (Secret Key)
response String (Required) The respond token by reCAPTCHA where sent from client submit form
remoteip String (Optional) The user's IP address.

Once we config API request correctly the data will respond as JSON below

{
  "success": boolean, //return true if user check box reCAPTCHA otherwise not
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) 
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

How to make request reCAPTCHA API in PHP? 

submit.php

<?php
  
if($_SERVER["REQUEST_METHOD"] === "POST")
{
    // Replace [your_secret_key] with your own secret key
    $recaptcha_secret = "[your_secret_key]";
    $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret
    ."&response=".$_POST['g-recaptcha-response']);
    // Convert string to JSON object
    $response = json_decode($response, true);
  
    if($response["success"] === true)
    {
        // Handle with your form data
        $email = $_POST["email"];
        $comment = $_POST["comment"];
        echo "Form submitted email: $email, $comment";
    }
    else
    {
        echo "Please check reCAPTCHA box";
    }
}

?>

Output

Conclusion

Google reCAPTCHA is so easy implement to add into website. You also can track the analytics reports of the CAPTCHA requests in admin panel. In example code we have demonstration very simple form with integrate Google reCAPTCHA, you can apply to any form in web app. Hope you learn how to prevent spam from submit form.

 

PHP 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him