PHP Contact Form with Google reCAPTCHA

Contact form with captcha code validation may be useful to validate a human user against bots. 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. 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

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.

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 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 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 class="label">Comments:</div>
    <div class="field">
        <textarea id="comment-content" name="content"
            placeholder="enter your comments here"></textarea>
    <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

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.

    $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!'));
	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.'));
	//reCAPTCHA validation
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());

		$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!'));
	$toEmail = "";
	$mailHeaders = "From: " . $user_name . "<" . $user_email . ">\r\n";
	if (mail($toEmail, "Contact Mail", $content, $mailHeaders)) {
	    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .', thank you for the comments. We will get back to you shortly.'));
	} else {
	    $output = json_encode(array('type'=>'error', 'text' => 'Unable to send email, please contact'.SENDER_EMAIL));

Contact Form with Google reCAPTCHA – Output

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


View Demodownload

This PHP code tutorial was published on January 9, 2018.

↑ Back to Top