PHP Contact Form with Google reCAPTCHA

by Vincy. Last modified on July 19th, 2022.

Contact form with Google reCAPTCHA code will be effective and efficient way of validating the user against bots. As we know already, the captcha is a concept specially for validating genuine human users against bots.

Integrating Google reCAPTCHA is recommended compare to the custom captcha code integration. In a previous tutorial, we have seen how to add captcha code in a form using PHP.

In this tutorial, we are going to integrate the Google reCAPTCHA in PHP contact form. Using this Google reCAPTCHA code, we can validate the human users and protect the form submission from bots.

In this example, I have autoloaded the dependencies of the Google reCAPTCHA code library. For using this library, we need to get the API keys by registering our site. If you want to know how to to get the reCaptcha API keys, then the steps that we have discussed in a previous article will be helpful.

After getting the API keys, I configured these keys to integrate Google reCAPTCHA code. In the contact form, the captcha code is shown and on the form submit this code is validated.

View Demo

google-recaptcha-widget-in-form

Contact Form with Google reCAPTCHA

This code is used to show the contact form to the user with the Google reCAPTCHA code. In this code, I have included the required Javascript resource file and rendered the reCAPTCHA widget by using a DIV element tagged with g-recaptcha.

In this tag, I have specified the API site key by using HTML5 data attribute data-site-key.

The following screenshot shows the Google reCAPTCHA widget rendered with the PHP contact form.

contact-form-with-google-recaptcha-output

When the user resolves the reCAPTCHA code, then the response token will be returned. A new HTML element g-recaptcha-response will be dynamically created to store the user’s response token.

This token will then be posted to the PHP code while submitting the contact form.

<form id="frmContact" action="" method="POST" novalidate="novalidate">
    <div class="label">Name:</div>
    <div class="field">
        <input type="text" id="name" name="name"
            placeholder="enter your name here"
            title="Please enter your name" class="required"
            aria-required="true" required>
    </div>
    <div class="label">Email:</div>
    <div class="field">
        <input type="text" id="email" name="email"
            placeholder="enter your email address here"
            title="Please enter your email address"
            class="required email" aria-required="true" required>
    </div>
    <div class="label">Phone Number:</div>
    <div class="field">
        <input type="text" id="phone" name="phone"
            placeholder="enter your phone number here"
            title="Please enter your phone number"
            class="required phone" aria-required="true" required>
    </div>
    <div class="label">Comments:</div>
    <div class="field">
        <textarea id="comment-content" name="content"
            placeholder="enter your comments here"></textarea>
    </div>
    <div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div>
    <div id="mail-status"></div>
    <button type="Submit" id="send-message" style="clear: both;">Send
        Message</button>
</form>

Google API Request from PHP Code to Validate reCAPTCHA

This PHP code reads google reCAPTCHA response token posted via the contact form. Then, it sends request to the API with this response token and the API secret key. After validating this token, the API will return JSON response.

<?php
if($_POST)
{
require('constant.php');
    
    $user_name      = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $user_email     = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $user_phone     = filter_var($_POST["phone"], FILTER_SANITIZE_STRING);
    $content   = filter_var($_POST["content"], FILTER_SANITIZE_STRING);
    
    if(empty($user_name)) {
		$empty[] = "<b>Name</b>";		
	}
	if(empty($user_email)) {
		$empty[] = "<b>Email</b>";
	}
	if(empty($user_phone)) {
		$empty[] = "<b>Phone Number</b>";
	}	
	if(empty($content)) {
		$empty[] = "<b>Comments</b>";
	}
	
	if(!empty($empty)) {
		$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' Required!'));
        die($output);
	}
	
	if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
	    $output = json_encode(array('type'=>'error', 'text' => '<b>'.$user_email.'</b> is an invalid Email, please correct it.'));
		die($output);
	}
	
	//reCAPTCHA validation
	if (isset($_POST['g-recaptcha-response'])) {
		
		require('component/recaptcha/src/autoload.php');		
		
		$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY);

		$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

		  if (!$resp->isSuccess()) {
				$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
				die($output);				
		  }	
	}
	
	$toEmail = "member@testdomain.com";
	$mailHeaders = "From: " . $user_name . "<" . $user_email . ">\r\n";
        $mailBody = "User Name: " . $user_name . "\n";
	$mailBody .= "User Email: " . $user_email . "\n";
	$mailBody .= "Phone: " . $user_phone . "\n";
	$mailBody .= "Content: " . $content . "\n";
	if (mail($toEmail, "Contact Mail", $mailBody, $mailHeaders)) {
	    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .', thank you for the comments. We will get back to you shortly.'));
	    die($output);
	} else {
	    $output = json_encode(array('type'=>'error', 'text' => 'Unable to send email, please contact'.SENDER_EMAIL));
	    die($output);
	}
}
?>

View Demodownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Contact Form with Google reCAPTCHA”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page