google recaptcha v3

Google reCAPTCHA V3 Tutorial with Example Demo in PHP

Google has launched reCAPTCHA v3 to prevent spam bots without any user interaction. reCAPTCHA v3 returns us spam score that can be used to take various action in your web app.

In this tutorial, I am going to show you how to integrate Google reCAPTCHA v3 on your website. If you are looking for reCAPTCHA v2, then click here to read the article covering reCAPTCHA v2.

LIVE DEMO DOWNLOAD

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 recaptcha v3 create app

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

  • Site key
  • Secret key

google recaptcha v3 credentials

Integrate Google reCAPTCHA in your website

To integrate it into your website you need to put it in the client side as well as in Server side. In 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 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.

Google reCAPTCHA v3

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 Form submit request we will check the POST variable.

form.php
<?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 '<h2>Please check the the captcha form.</h2>';
    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.

google recaptcha v3 response

Further reading

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

27 Comments

  1. I was searching how to upgrade from v2 to v3 and i ended up with this page. Great article, thanks for sharing. But i must tell, there is a redundancy in these codes. On the client side, you are sending ajax request and adding the token with the field name of “token” already, thus you don’t have to prepend the hidden g-recaptcha-response input field to the DOM at all. If you disable Ajax post and make a ordinary post-back request to form.php; then the prepended hidden input field’s “name” attribute must have been “token” instead of “g-recaptcha-response”, so the form.php would read it correctly 😉

    1. “If you disable Ajax post and make an ordinary post-back request to form.php; then the prepended hidden input field’s “name” attribute must have been “token” instead of “g-recaptcha-response”, so the form.php would read it correctly” – With reCAPTCHA 3 you can’t do that normal form submit. I either had to stop the form submit and append a new field which would be google captcha response or do via Ajax. I like Ajax so…

  2. Hi, thank you for this example!
    When you check for recaptcha answer shouldn’t it be
    if(result.success===’true’) { […]
    instead of
    if(result.success) { […] ?
    In the latter case “result.success” is always true I think

    1. Hi, I am returning a boolean value from PHP so result.success would work. It will check whether success key exists or not and if exists whether it’s true or not. For any value other than that, the else block will be executed.

  3. Hi, do i understand correctly, this code verifies the captcha both in the frontend and in the backend (form.php)? If i use it on an order entry form which should:

    a) display a custom HTML content once the order has been placed
    b) send an email to the customer and to the page owner

    do i have to integrate the code for a) and b) here:

    if(result.success) {
    alert(‘Thanks for posting comment.’)
    } else {
    alert(‘You are spammer ! Get the @$%K out.’)
    }

    ?

    Thank you in advance.

    Regards,
    Marco

  4. Hi, thanks for this tutorial! Do i understand correctly, both the frontend and the backend are verifying the Captcha?

    If i want to use this in an order entry form which should:

    a) Display a confirmation (html table)
    b) send an email

    .. do i have to implement the code for a) and b) in the “if($responseKeys” section of the form.php?

    Thank you in advance and best Regards,
    Marco

  5. Hi Shahid,
    Can you help me with logic of form.php in jsp . I am trying to implement google recaptcha version 3 in java/jsp . But i didnt find any tutorial for that.

      1. Asking about Java, I would say the codebase is in same directory. And previously spring security is being used to verify username and password. How we will integrate this reCaptcha token in this Spring security check.

  6. This tutorial is good, but quite unsecure.
    Don’t post your secret for verifying with a GET-Method.
    Google wants you to make an POST-Method api call. If you do it like in this tutorial,
    your secret will be readable for everyone, who sniffs the packets.
    Please correct this Tutorial, as I wrote in the mail.

  7. Hello,
    Thanks for your tutorial. Its working for me. But, Im facing odd issue. That’s is my website getting minimum 5000 to 8000 user entries per day. I’m getting score for 99% users. Which means 40 to 60 users didn’t get reCAPTCHA token and even grecaptcha.execute function also not working. But grecaptcha.ready is working. How to resolve this issue. Please save me. I’m struggling with this issue for past few weeks. Why reCAPTCHA token not getting for few users?

  8. Thanks for your tutorial.
    Does this code still work? I copied the code for index.html and form.php, inserted the recaptcha V3 codes for my site.
    But after submitting the form nothing happens.
    I checked both V3 sidekey & secretkey but they are fine 🙁

    Thanks for any advice.

  9. Hi! everything looks fine and I guess this works. Hard to say because it doesn’t show any changes. I just wonder why it doesn’t show comment “Thanks for posting comment” as in your example.
    Any ideas? In any case thank you for this post

  10. Thanks, way better than official documentation on Google site, I reused the frontend and changed Google’s backend implementation of a Java servlet to make it run in tomcat, works like a charm

  11. Hi Shahid,
    Thank you for the description.
    I use WordPress for my sites and have pages some have as an example both contact and review form on it. should I insert the script on both forms or will it be enough to use it only on one of them?
    thanks. 🙂

  12. Thanks for this!:) One could also leave out the JSON-header in the form.php and instead parse the JSON from the response in the index.html -> JSON.parse(result).success)

  13. Thanks mate, I wasn’t sure why mine wasn’t working and seems that it was expecting encoded as form data rather than json, would never have realised as their docs are not ideal
    👍

  14. Can’t thank you enough for this tutorial. I was able to completely refactor it for use with my code, and I also learned some new Javascript tricks!

    Really appreciate you taking the time to create such a logical and direct example.

  15. Thanks mate for this tutorial, everything works fine!!! Maybe you can help how to improve in your example badge position from default “bottomright” to “bottomleft”?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.