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

PHP
Nakul Kumar · · 24442 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:

Learn PHP Development from beginning.

PHP stance Hypertext Preprocessor, it's server-side scripting laungage and easy to use. PHP  also well  known for its speed, simplicity, flexibility features that have made it (...)
Programmer Desk

What is the difference between classes vs enums in PHP 8.1?

One of the common questions that I have been asked is what is the difference between classes and enums. Class(es) and enum(s) share many similarities but differ in some aspects. (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar

What is Enumerations(Enums) in PHP 8.1? Enums in PHP v8.1 Explained in detail with examples.

PHP 8.1 added many new features, and Enumerations (Enum) is our favourite new feature. Enumerations (or enums for short) allow us to define a new structure similar to a class however (...)
Harish Kumar

Web App Development Technologies

If you have been planning to create robust websites or web apps, you should be aware of the various technologies required to make it happen. Over time, these technologies have (...)
Narola Infotech

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