Menu Close

Integrate Google reCAPTCHA in PHP 8 Contact Form

google recaptcha - codeamend

Google reCAPTCHA is the best option to protect web forms from spam. The reCAPTCHA is a robust spam security tool that makes sure you are a real human, and Google reCaptcha checkbox also provides the best user experience in a few lines of codes.

google recaptcha

Google released reCAPTCHA version 3 recently, and version 2 was also there to protect against bad bots. To improve the productivity of Contact forms, we must execute the reCAPTCHA code in our sites. It validates the contact form with a single tick, and it stops bots from sending spam mails.

Implementing Google reCaptcha code in PHP contact form is very simple and useful from the UX perspective. This tool specially designed for checking natural human users against the bad bots. A user has to click on a checkbox to confirm his identity. Simple, Isn’t It.

Usually, Google reCAPTCHA is used to protect from bots; however, you can also validate any response generated from your web app with reCAPTHA.

Generate reCAPTCHA Site & Security API Keys

We must include Google reCaptcha Site and Secret Key, and it requires you to register your domain which needs to be protected against spam.

Visit the reCAPTCHA website and register your application.

Enter the Label name. It helps you recognize your registered domain name.

We can see reCAPTCHA versions 3 and 2 and select reCAPTCHA v2 > I’m not a robot option by selecting the radio button.

Enter your domain name, which requires protection from bots.

create google recaptcha

Click on the “Save” button, you will be redirected to a new page.

Copy your reCAPTCHA Site Key and Secret Key, we will need these API keys in the next step.

Integrate Google reCAPTCHA in PHP Contact Form

To add the Google reCAPTCHA Widget in HTML Form, we need to place the reCAPTCHA JavaScript file at the bottom of the web page. Just paste the following link before the body tag closes.

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

Next, include the g-recaptcha HTML tag inside the HTML Form element, and place it exactly where you would like to show the reCAPTHCA tool.

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

Specify the name property in input fields that interacts with the PHP API, Define the alert box to display success and error messages.

//index.php
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Codeamend 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="style.css">
    </head>
    <body>
        <div class="container mt-5">
            <h2>Implement Google reCAPTCHA in PHP Contact Form</h2>
            <?php include('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="Your_Site_Key"></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 makes sure the user has entered the required values or not. Google reCAPTCHA response is triggered based 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.

//form.php
<?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 = 'Your_Secret_Key';
                // 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 = "text@codeamend.com";
                        $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."
            );
        }
    }  
?> 
//style.css
.container {
    max-width: 500px;
    margin: 50px auto;
    text-align: left;
    font-family: sans-serif;
}

form {
    border: 1px solid #1A33FF;
    background: #ecf5fc;
    padding: 40px 50px 45px;
}

.form-control:focus {
    border-color: #000;
    box-shadow: none;
}

label {
    font-weight: 600;
}

.error {
    color: red;
    font-weight: 400;
    display: block;
    padding: 6px 0;
    font-size: 14px;
}

.form-control.error {
    border-color: red;
    padding: .375rem .75rem;
} 

Google reCAPTCHA in PHP Contact Form Example

Here is the screenshot that describes the Google reCAPTCHA checkbox widget that we added to the PHP contact form.

google recaptcha output

Conclusion

We have completed the PHP Google reCAPTCHA tutorial. We have learned how to integrate Google reCAPTCHA in PHP Form easily. Also, learn to implement server-side validation to Google reCAPTCHA version 2.

You can also check out the CAPTCHA analytics to figure out the request flow.

Posted in PHP

You can also read...