How to Add Google reCAPTCHA to a PHP Form with Example?

PHP
Nakul Kumar · · 1071 Views

In this guide, we will integrate the Google reCAPTCHA in the PHP contact form. Utilizing this Google reCAPTCHA code, we can validate the human users and protect the form of submission from bots.

Integrating Google reCAPTCHA is recommended because It is an effective and efficient way of validating the user against bots. As we know already, the captcha is an idea particularly for validating real human users against bots.

How to Add Google reCAPTCHA to a PHP Form with Example?

Here are the steps for integrating the Google reCAPTCHA:

  1. Get Google reCaptcha API Key.

  2. Create an HTML form.

  3. Integrate reCAPTCHA in a PHP form.

  4. Validate the response with Google reCAPTCHA.

Get Google reCaptcha API Key

To get the Google reCaptcha API key, you first have a Google account. And login into your Google account and visit this site https://www.google.com/recaptcha/admin.

Here you need to define the label name, the domain name in which you need to integrate Google reCaptcha.

How to Add Google reCAPTCHA to a PHP Form with Example?

Click on the "Save" button, and you will be redirected to a new page.

How to Add Google reCAPTCHA to a PHP Form with Example?

Copy your reCAPTCHA Site Key and Secret Key. We will require these API keys in the following step.

Integrate Google reCAPTCHA in PHP Contact Form

To add the Google reCAPTCHA Widget in HTML Form, we need to put the reCAPTCHA JavaScript file on the web page. So, paste the following link before the body tag closes.

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

Next, add the g-recaptcha HTML tag inside the HTML Form, place it exactly where you might want to show the reCAPTHCA widget.

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

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

Here is the code for the Contact form:

<!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 ensures if the user has entered the necessary values or not. Google reCAPTCHA response is set off dependent 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 = "[email protected]";
                        $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."
            );
        }
    }  
?>

So, this was the complete step by step process for utilizing Google reCaptcha with PHP and validate response using Ajax with PHP. I hope this article helped you to easy to understand how to integrate Google reCAPTCHA checkbox using PHP.

0

Please login or create new account to add your comment.

0 comments
You may also like:

How to Upload Multiple Images with jQuery AJAX and PHP, with preview

Uploading an image without page refresh is more user-friendly than refreshing the entire page. So, in this guide, you will learn how to upload multiple images using ajax in jQuery (...)
Nakul Kumar

What's new in PHP 8: New Features and Improvements

PHP 8.0 is a major update of the PHP language. It contains a range of new features and optimizations such as the JIT compiler, union types, attributes, constructor property promotion, (...)
Harish Kumar

How To Install LEMP stack (Linux, Nginx, MySQL, PHP) on Ubuntu System

The term LEMP is an acronym of the four open-source projects:
Harish Kumar

How to connect a PostgreSQL database server using PHP PDO?

Before connecting with the PostgreSQL database using PHP PDO, make sure PHP PDO PostgreSQL driver enabled.
Razet

How to create PHP Pagination using PDO with example?

In this example, I am going to show you how to create pagination in PHP using PDO.First, create a DatabaseConnection.php to create a database connection.
Razet

PHP PDO tutorial with CRUD operation example

One of the most significant PHP extension is called PHP Data Objects or PDO, which was available since PHP 5.0. PDO gives an interface to working with different RDBMS, including (...)
Razet