X

PHP Contact Form with Google reCAPTCHA V3 Example

Contact form with Google reCAPTCHA Code will be an efficient and effective way to validate the user against bots. The captcha, as we all know, is an idea that can be used to validate human users against bots.

To increase your sales, check out Iris’s best contact form. It is optimized for high conversion. This contact form is optimized for frictionless UI/UX, which will lead to increased inquiries. It features many features, including Google reCAPTCHA and multiple attachments.

Google reCAPTCHA integration is preferred to custom captcha code implementation. We have already seen how to add captcha code to a form with PHP.

This tutorial will show you how to embed the Google reCAPTCHA into a PHP contact form. This Google reCAPTCHA code allows us to validate human users and protect submissions from bots.

In this example, I have automatically loaded the dependencies for the Google reCAPTCHA Code library. Registering your site will give you the API keys that allow you to use this library. The steps we discussed in a previous article can be used to help you get the reCaptcha API key keys.

After obtaining the API keys, I set these keys up to integrate Google’s reCAPTCHA code. The contact form displays the captcha code and the form submit validates it.

Google reCaptcha is a security service that prevents bots from sending you automatic emails on your public forms, reCaptcha is used for human verification owned by Google. Google reCAPTCHA v3 is invisible you won’t see it in your forms create your form without adding a captcha checkbox it’s integrated with your submit button.

reCaptcha v3 Example & Download

Step 1:

Create your captcha app from here: https://www.google.com/recaptcha/admin/create

Once you create your app it will give you Site Key and Secret Key.

Use the site key in the HTML code your site serves to users.

Use the secret key for communication between your site and reCAPTCHA.

Now create HTML Form available here

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!------ Include the above in your HEAD tag ---------->



<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<div class="container">

    <div class="row justify-content-center">

		<div class="col-12 col-md-8 col-lg-6 pb-5">





                    <!--Form with header-->



                    <form action="send.php" method="post" id="submitForm">

                        <div class="card border-primary rounded-0">

                            <div class="card-header p-0">

                                <div class="bg-info text-white text-center py-2">

                                    <h3><i class="fa fa-envelope"></i> Contact Form</h3>

                                    <p class="m-0">Google reCaptcha Example</p>

                                </div>

                            </div>

                            <div class="card-body p-3">



                                <!--Body-->

                                <div class="form-group">

                                    <div class="input-group mb-2">

                                        <div class="input-group-prepend">

                                            <div class="input-group-text"><i class="fa fa-user text-info"></i></div>

                                        </div>

                                        <input type="text" class="form-control" id="name" name="name" placeholder="Name" required>

                                    </div>

                                </div>

                                <div class="form-group">

                                    <div class="input-group mb-2">

                                        <div class="input-group-prepend">

                                            <div class="input-group-text"><i class="fa fa-envelope text-info"></i></div>

                                        </div>

                                        <input type="email" class="form-control" id="email" name="email" placeholder="Email" required>

                                    </div>

                                </div>



                                <div class="text-center">

                                <button data-sitekey="reCAPTCHA_site_key" data-callback="onSubmit" data-action="submit"  class="g-recaptcha btn btn-info btn-block rounded-0 py-2">Send</button>	

                                    

                                </div>

                                <div id="message"></div>

                            </div>



                        </div>

                    </form>

                    <!--Form with header-->





                </div>

	</div>

</div>

This button code will submit the form through JavaScript

<button data-sitekey="reCAPTCHA_site_key" data-callback="onSubmit" data-action="submit" class="g-recaptcha btn btn-info btn-block rounded-0 py-2">Send</button>

You have to add your site key in the place of reCAPTCHA_site_key

Load JavaScript API

<!-- captcha -->

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

Load jQuery

<!-- jQuery -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Callback function to handle form

<script>

    function onSubmit(token) {

        var formData = $("#submitForm").serialize();

        $(".has-error").removeClass("has-error");

        if ($("#name").val() == "")

        {

            $("#message").html("Enter Name.");

            return false;

        }

        if ($("#email").val() == "")

        {

            $("#message").html("Enter Email.");

            return false;

        }

        $.ajax({

            url: "send.php",

            type: "POST",

            data: formData,

            success: function (data) {

                $("#submitForm")[0].reset();

                // console.log(data)

                $("#message").html(data)

            },

            error: function() {

                alert("error handling here");

            }

        });

    }

</script>

This JavaScript function submits your data to send.php.

<?php

$captchaSecretKey = "Your_Secret_key";

//reCAPTCHA validation

if (isset($_POST['g-recaptcha-response'])) {



	$postData = array(

		'secret' => $captchaSecretKey,

		'response' => $_POST['g-recaptcha-response']

    );

    $url = "https://www.google.com/recaptcha/api/siteverify";



	$curl = curl_init();

	curl_setopt($curl, CURLOPT_URL, $url);

	curl_setopt($curl, CURLOPT_POST, true);

	curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));

	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

	$serverResponse = curl_exec($curl);



	if(json_decode($serverResponse,true)['success'] == 1)

	{

		echo '<b>Captcha</b> Validated!';

		exit;

	}

	else

	{

		echo '<b>Captcha</b> Validation Required!';

		exit;

	}	

}

?>

Your_Secret_key replace with your Secret Key

This file verifies your submitted captcha and responds accordingly.

Huzoor Bux: I am a PHP Developer

View Comments (6)