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

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

Exploring Asymmetric Property Visibility in PHP 8.4

The release of PHP 8.4 introduces a powerful new feature: Asymmetric Property Visibility, enabling developers to define separate visibility rules for reading and writing properties. (...)
Harish Kumar

What's New in PHP 8.4: Key Enhancements and Updates

As PHP 8.4's release on November 21, 2024, approaches, it's clear that PHP continues to evolve and delight its developer community. For those who have been coding with PHP since (...)
Harish Kumar

Introducing Tools to Supercharge PHP-FPM Efficiency and Monitoring

PHP-FPM stands for PHP FastCGI Process Manager. It’s an improved way to manage PHP processes that makes web applications faster and more efficient. Instead of running each PHP (...)
Harish Kumar

PHP 8.4 Property Hooks: The Ultimate Guide for Developers

PHP 8.4, coming in November 2024, introduces a new feature called property hooks. This feature makes it easier to work with class properties by allowing you to define custom behavior (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

PHP Security Guide: Strategies for Safe and Secure Code

PHP is one of the most widely used server-side scripting languages for web development, powering millions of websites and applications. Its popularity is largely due to its ease (...)
Harish Kumar