Laravel & Php

Google reCAPTCHA V3 In PHP


Google reCAPTCHA V2 In PHP

Register your website and get Secret Key.

Very first thing you need to do is register your website on Google recaptcha to do that click here.

Login to your Google account and create the app by filling the form. Select the reCAPTCHA v3 and in that select “I am not a robot” checkbox option.

Google recapture

Once submitted, Google will provide you with the following two information.

  • Site key
  • Secret key
google recapture
google recapture

Integrate Google reCAPTCHA in your website

To integrate it into your website you need to put it on the client-side as well as on the server-side. In the client HTML page, you need to integrate this line before the tag.

<script src="https://www.google.com/recaptcha/api.js?render=put your site key here">script>

Google reCAPTCHA v3 is invisible. You won’t see a captcha form of any sort on your web page. You need to capture the google captcha response in your JavaScript code. Here is a small snippet.

<script src="https://www.google.com/recaptcha/api.js?render=put your site key here">script>
<script>
grecaptcha.ready(function() {
    grecaptcha.execute('put your site key here', {action: 'homepage'}).then(function(token) {
      // pass the token to the backend script for verification
    });
});
script>

Let’s look at the sample code to understand it better.

Sample project

Here is the HTML code to render the reCAPTCHA on the front-end.

index.html

<html>
  <head>
    <title>Google recapcha v3 demo - Codeforgeek</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post" >
      <input type="email" name="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
    </form>
      <script>
       // when form is submit
    $('#comment_form').submit(function() {
        // we stoped it
        event.preventDefault();
        var email = $('#email').val();
        var comment = $("#comment").val();
        // needs for recaptacha ready
        grecaptcha.ready(function() {
            // do request for recaptcha token
            // response is promise with passed token
            grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
                // add token to form
                $('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
                    $.post("form.php",{email: email, comment: comment, token: token}, function(result) {
                            console.log(result);
                            if(result.success) {
                                    alert('Thanks for posting comment.')
                            } else {
                                    alert('You are spammer ! Get the @$%K out.')
                            }
                    });
            });;
        });
  });
  </script>
  </body>
</html>

This will generate the following form.

and if you notice, on the right end corner, you will see a Google reCAPTCHA icon.

Since we don’t have a checkbox-style captcha, we need to capture the Google reCAPTCHA response and send it to the back end for verification.

In the code, on the form submit we are getting the token using the execute() function of reCAPTCHA and passing the token along with email and comment to the PHP code using jQuery Ajax function.

On the server-side, we are going to use PHP for now. So on the Form submit an event, we will check the POST variable.

form.php

$email;$comment;$captcha;
  $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
  $comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
  $captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
  if(!$captcha){
    echo '
Please check the the captcha form.
';
    exit;
  }
  $secretKey = "-----put your secret here------";
  $ip = $_SERVER['REMOTE_ADDR'];

  // post request to server
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array('secret' => $secretKey, 'response' => $captcha);

  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
  );
  $context  = stream_context_create($options);
  $response = file_get_contents($url, false, $context);
  $responseKeys = json_decode($response,true);
  header('Content-type: application/json');
  if($responseKeys["success"]) {
    echo json_encode(array('success' => 'true'));
  } else {
    echo json_encode(array('success' => 'false'));
  }
?>

Run the code and fill the form. If you are not recognized as a spammer by Google, you will see an alert box showing the following message.


PHP
Share with Friends

Like this chef? Share with friends..