PHP Contact Form with Google reCAPTCHA

If you do not know how to add Google reCaptcha in PHP form, then you have come on the right place. Because in this post you can find the solution of How to integrate Google reCaptcha in PHP form and here you can also find how to validate PHP form with Google reCaptcha by using Ajax jQuery.

Form data has been validated with Google reCaptcha is required because we all know spamming is one of the very common problems which has been faced on the web. Every Website owner prevents their website from invalid spam traffic or spam comment.

Before the programmer has used random captcha code to preventing spamming or bots filled in their website form. But this is an old method and now most of the web application has been used Google reCAPTCHA, for verify that form input field has been filled by any human. Google reCAPTCHA is very simple to verify that he is a user. User can verify just in a single click for that they are not a robot.

Below you can find the details step by step which guides you for How to build PHP spam-free contact form by using Google reCaptcha.

Step 1: Get Google reCaptcha API Key

For getting Google reCaptcha API key, you first have Google account. If you have google account, then login into your Google account and visit this website https://www.google.com/recaptcha/admin.

Once you have visit above link then, you can see above image web page. Here you have to define label name, the domain name in which you want to integrate Google reCaptcha and click on submit button. Here we want to use in localhost also so we have include localhost in domain list also. And lastly, click on the submit button, then you can get API key, which you can see below.

Add Google reCaptcha API key in your web page

In this tutorial, we will create our HTML form in index.php file. So, in this file first, we need to add a reCAPTCHA javascript library in our HTML code.

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

After this, we want to add the following HTML code to generate the Google reCAPTCHA widget in the form.

<div class="g-recaptcha" data-sitekey="Enter Here Your Sitekey"></div>

Here in data-sitekey value, we have to add site key which we have got from Google reCAPTCHA API key. Once you have added this code and refresh web page then Google reCaptcha widget will be created in your web page. Below you can source code of index.php file

index.php

<html>  
    <head>  
        <title>PHP Contact Form with Google reCAPTCHA</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>  
    <body>  
        <div class="container" style="width: 600px">
   <br />
   
   <h3 align="center">PHP Contact Form with Google reCAPTCHA</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Registration Form</div>
    <div class="panel-body">
     
     <form metod="post" id="captcha_form">
      <div class="form-group">
       <div class="row">
        <div class="col-md-6">
         <label>Your First Name <span class="text-danger">*</span></label>
         <input type="text" name="your_first_name" id="your_first_name" class="form-control" />
         <span id="your_first_name_error" class="text-danger"></span>
        </div>
        <div class="col-md-6">
         <label>Your Last Name <span class="text-danger">*</span></label>
         <input type="text" name="your_last_name" id="your_last_name" class="form-control" />
         <span id="your_last_name_error" class="text-danger"></span>
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Your Email Address <span class="text-danger">*</span></label>
       <input type="text" name="your_email" id="your_email" class="form-control" />
       <span id="your_email_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <label>Password <span class="text-danger">*</span></label>
       <input type="password" name="your_password" id="your_password" class="form-control" />
       <span id="your_password_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <div class="g-recaptcha" data-sitekey="6Ldv2bcUAAAAAFeYuQAQWH7I_BVv2_2_vvmn2Fpp"></div>
       <span id="captcha_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" class="btn btn-info" value="Register" />
      </div>
     </form>
     
    </div>
   </div>
  </div>
    </body>  
</html>

<script>
$(document).ready(function(){

 $('#captcha_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"request_process_data.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#register').attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#register').attr('disabled', false);
    if(data.success)
    {
     $('#captcha_form')[0].reset();
     $('#your_first_name_error').text('');
     $('#your_last_name_error').text('');
     $('#your_email_error').text('');
     $('#your_password_error').text('');
     $('#captcha_error').text('');
     grecaptcha.reset();
     alert('Form Successfully validated');
    }
    else
    {
     $('#your_first_name_error').text(data.your_first_name_error);
     $('#your_last_name_error').text(data.your_last_name_error);
     $('#your_email_error').text(data.your_email_error);
     $('#your_password_error').text(data.your_password_error);
     $('#captcha_error').text(data.captcha_error);
    }
   }
  })
 });

});
</script>

Validate User Response at Server-side

We need to validate the user response at server-side after this, for this, we have to request_process_data.php file, in which by using Ajax the reCAPTCHA response data will be received. When a user submits a form, then reCAPTCHA widget response has been received at request_process_data.php using Ajax. By following the PHP script we need to verify the response.

if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = 'Your Secret Key';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }

Here in secret key variable, we need to define secret key which we have got from Google reCaptcha website. Here you need to define your secret key which you have get at the time of generating Google reCAPTCHA API key.

For validating user response here we have sent the request to Google reCAPTCHA API URL for check user response is proper or not using file_get_contents() function. Below you can find complete PHP script for validating form data with Google reCAPTCHA response also.

request_process_data.php

<?php

//request_process_data.php

if(isset($_POST["your_first_name"]))
{
 $first_name = '';
 $last_name = '';
 $email = '';
 $password = '';

 $your_first_name_error = '';
 $your_last_name_error = '';
 $your_email_error = '';
 $your_password_error = '';
 $captcha_error = '';

 if(empty($_POST["your_first_name"]))
 {
  $your_first_name_error = 'First name is required';
 }
 else
 {
  $first_name = $_POST["your_first_name"];
 }

 if(empty($_POST["your_last_name"]))
 {
  $your_last_name_error = 'Last name is required';
 }
 else
 {
  $your_last_name = $_POST["your_last_name"];
 }
 if(empty($_POST["your_email"]))
 {
  $your_email_error = 'Email is required';
 }
 else
 {
  if(!filter_var($_POST["your_email"], FILTER_VALIDATE_EMAIL))
  {
   $your_email_error = 'Invalid Email';
  }
  else
  {
   $your_email = $_POST["your_email"];
  }
 }

 if(empty($_POST["your_password"]))
 {
  $your_password_error = 'Password is required';
 }
 else
 {
  $your_password = $_POST["your_password"];
 }

 if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = 'Your Secret Key Here';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }

 if($your_first_name_error == '' && $your_last_name_error == '' && $your_mail_error == '' && $your_password_error == '' && $captcha_error == '')
 {
  $data = array(
   'success'  => true
  );
 }
 else
 {
  $data = array(
   'your_first_name_error' => $first_name_error,
   'your_last_name_error' => $last_name_error,
   'your_email_error'  => $email_error,
   'your_password_error' => $password_error,
   'captcha_error'  => $captcha_error
  );
 }

 echo json_encode($data);
}

?>

So, this was the complete process step by step for using Google reCaptcha for Contact form validate with PHP and get a response using Ajax (jQuery) with PHP. We hope you can understand how to integrate Google reCAPTCHA checkbox using PHP.

Leave a reply:

Your email address will not be published.

Site Footer