Wednesday 11 September 2019

PHP Form with Google reCaptcha



If you not know how to add Google reCaptcha in PHP form, then you have come on right place. Because in this post you can find 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 validate with Google reCaptcha is required because we all know spamming is one of very common problem which has been faced on web. Every Website owner prevent their website from invalid spam traffic or spam comment.

Before programmer has used random captcha code for prevent spamming or bots filled in their website form. But this is 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 user. User can verify just in single click for that they are not a robot.

Below you can find step by step guide for How to build PHP spam free form by using Google reCaptcha.



Step 1: Get Google reCaptcha API Key


For get 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, 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 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 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 following HTML code for generate Google reCAPTCHA widget in form.


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


Here in data-sitekey value, we have to add site key which we have get from Google reCAPTCHA api key. Once you have add 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>How to Implement Google reCaptcha in PHP Form</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">How to Implement Google reCaptcha in PHP Form</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register 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>First Name <span class="text-danger">*</span></label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <span id="first_name_error" class="text-danger"></span>
        </div>
        <div class="col-md-6">
         <label>Last Name <span class="text-danger">*</span></label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Email Address <span class="text-danger">*</span></label>
       <input type="text" name="email" id="email" class="form-control" />
       <span id="email_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <label>Password <span class="text-danger">*</span></label>
       <input type="password" name="password" id="password" class="form-control" />
       <span id="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:"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();
     $('#first_name_error').text('');
     $('#last_name_error').text('');
     $('#email_error').text('');
     $('#password_error').text('');
     $('#captcha_error').text('');
     grecaptcha.reset();
     alert('Form Successfully validated');
    }
    else
    {
     $('#first_name_error').text(data.first_name_error);
     $('#last_name_error').text(data.last_name_error);
     $('#email_error').text(data.email_error);
     $('#password_error').text(data.password_error);
     $('#captcha_error').text(data.captcha_error);
    }
   }
  })
 });

});
</script>


Validate User Response at Server side


After this we need to validate user response at server side, for this we have to process_data.php file, in which recaptcha response data will be received using Ajax. When user submit form, then reCAPTCHA widget response has been received at process_data.php using Ajax. Here we need to verify response by following php script.


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

  $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 get 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 validate user response here we have send 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 validate form data with Google recaptcha response also.

process_data.php


<?php

//process_data.php

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

 $first_name_error = '';
 $last_name_error = '';
 $email_error = '';
 $password_error = '';
 $captcha_error = '';

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

 if(empty($_POST["last_name"]))
 {
  $last_name_error = 'Last name is required';
 }
 else
 {
  $last_name = $_POST["last_name"];
 }
 if(empty($_POST["email"]))
 {
  $email_error = 'Email is required';
 }
 else
 {
  if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
  {
   $email_error = 'Invalid Email';
  }
  else
  {
   $email = $_POST["email"];
  }
 }

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

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

  $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($first_name_error == '' && $last_name_error == '' && $email_error == '' && $password_error == '' && $captcha_error == '')
 {
  $data = array(
   'success'  => true
  );
 }
 else
 {
  $data = array(
   'first_name_error' => $first_name_error,
   'last_name_error' => $last_name_error,
   'email_error'  => $email_error,
   'password_error' => $password_error,
   'captcha_error'  => $captcha_error
  );
 }

 echo json_encode($data);
}

?>


So, this was the complete step by step process for using Google reCaptcha with PHP and validate response using Ajax with PHP. We hope you can understan how to integrate Google reCAPTCHA checkbox using PHP.

9 comments:

  1. where is email function header content subject

    ReplyDelete
  2. There is a bug in this form. Google handles the recaptcha validation if you click on it so the code that says "recaptcha failure" is redundant. The problem with the code is if someone fills out everything accept one field (e.g. password) and has already done the recaptcha correctly (shows check mark)....when you click registrar...it will send the verification to google for validation. Then if you fill out the password and try to resubmit the form and google will think recaptcha has a failure since it was already submitted once. So you need to modify the processing_data.php file so the else clause of the recaptcha on submits the request for validation to Google only if there is no other error on the form:

    if(empty($_POST['g-recaptcha-response']))
    {
    $captcha_error = 'Captcha is required.';
    }
    else
    {
    $secret_key = '6Ldv2bcUAAAAAFXUKdLW_qljFd9FpxNguf06DHhp';

    if($first_name_error == '' && $phonenum_error == '' && $email_error == '' && $password_error == '' && $captcha_error == '')
    {
    $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. Refresh page to reload if necessary.';
    }
    }
    }

    ReplyDelete
  3. sir plz help me when i click your registered button after checkbox click no respond came but without checkbox all worked fine ,i copied your index.php and process_data.php in my file with same name.
    i am very tried plz help me sir

    ReplyDelete
  4. no error found after click registered button when i clicked checkbox then only registered button disabled and no error came

    ReplyDelete
  5. without click the checkbox it's success. why?

    ReplyDelete
  6. it's working but when we check the box that time to varied image not show directlt it take automatic the mark ...plz help me..to reslove this problem...i have same file as you include index.php and process_data.php

    ReplyDelete
  7. I did everything step by step with the comment of Vincenzo but when i press the Register-button nothing happens. Please, can someone help me?!

    ReplyDelete