Google reCAPTCHA v3 Implementation in PHP form without Ajax

Google reCAPTCHA v3 integration
Written by Gupta

Google reCAPTCHA v3 is one of the best and popular tools to prevent spam and bots request on any form. It prevents robots to send any request by form on the webpage.

Google has launched v3 of reCAPTCHA where spam and bots requests have been prevented without any user interaction. It works on a score basis. The score resides between 0.0 to 1.0 where 0.5 and its above represents human and less than 0.5 represents a robot.

In this tutorial, I am going to share how to implement Google reCAPTCHA v3 in PHP without using Ajax? Here, you are reading “without using ajax” that means when you are submitting your form directly with the help of form action attribute means by not using ajax to submit your form then this article will help you to implement Google reCAPTCHA v3 in an easy way.

An important thing to implement Google reCAPTCHA v3 in your project

You must have the following details to implement Google reCAPTCHA v3 in your project.

  • First, you need a Gmail account to register on reCAPTCHA website
  • Second, you have a site key and secret key. You will find the site key and secret key by registering on the reCAPTCHA website.

Register on reCAPTCHA website

In this step, I will explain how can you register on the Google reCAPTCHA website to get a site key and secret key to implement on your project. Let’s follow these steps:

Google reCAPTCHA v3 form
Google reCAPTCHA v3 form

Step 1: First of all, go to the reCAPTCHA website by following this link: Click here for reCAPTCHA official site

Step 2: Next, click on the Admin Console and log in with your Gmail account

Step 3: After that, register your site by clicking on the plus icon. Plus icon resides on the top right. In register your site box, you have to fill these details. Let me explain…

  • Label: You can write any label name which is suitable for your website or project.
  • reCAPTCHA type: select reCAPTCHA v3
  • Domains: Add your domain lists one by one. You can use the same site key and secret key on multiple websites by adding domains here. If you are implementing reCAPTCHA on localhost then you have to add two domains localhost and 127.0.0.1 because in some cases the only localhost does not work.
  • Accept the reCAPTCHA Terms of Service: Tick this checkbox

Step 4: Finally, submit this form and you will get a site key and secret key.

Client-side integration of reCAPTCHA v3

To show you the integration process of reCAPTCHA v3, I have created a simple form. In this form, there is only one text field (Name) and two hidden input fields to contain token and action which will be generated after reCAPTCHA execute at the client-side.

There is a submit button on the form to submit the form data. Here, I am linking two scripts one is for Google reCAPTCHA API and another one is for jQuery. Here, I am using jQuery to set token and action input field value by their id.

Now, the reCAPTCHA script has been written to generate a token at the client-side with the help of their API. After generating the token, I have set the token and action input field value by their respective id.

In this process, I am executing the reCAPTCHA API at the fixed interval of time (3 seconds) to generate a new token. This will help you when the user takes too much time to fill the form because the reCAPTCHA token is valid only for a few minutes. You can change it according to your requirements.

index.php

<!DOCTYPE html>
<html>
   <head>
      <title>Google Recaptcha V3</title>
   </head>
   <body>
      <h1>Google Recaptcha V3</h1>
      <form action="recaptcha.php" method="post">
         <label>Name</label>
         <input type="text" name="name" id="name">
         <input type="hidden" name="token" id="token" /> 
         <input type="hidden" name="action" id="action" /> 
         <input type="submit" name="submit">
      </form>
      <script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
      <script  src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
      <script type="text/javascript">
         $(document).ready(function(){
         	setInterval(function(){
         	grecaptcha.ready(function() {
         	    grecaptcha.execute('put your site key here', {action: 'application_form'}).then(function(token) {
         	    	$('#token').val(token);
         	    	$('#action').val('application_form');
         	    });
         	});
         	}, 3000);
         });
         
      </script>
   </body>
</html>

The form result looks like this image.

Google reCAPTCHA demo
Google reCAPTCHA demo

Server-side integration of reCAPTCHA v3

At the server-side, I have received all three input field values (name, token and action) and then executing a cURL command to send a token and secret key as request and getting response data.

recaptcha.php

<?php

if ($_POST['submit']) {
    $name   = $_POST['name'];
    $token  = $_POST['token'];
    $action = $_POST['action'];
    
    $curlData = array(
        'secret' => 'put your secret key here',
        'response' => $token
    );
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curlResponse = curl_exec($ch);
    
    $captchaResponse = json_decode($curlResponse, true);
    
    if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) {
        echo 'Form Submitted Successfully';
    } else {
        echo 'You are not a human';
    }
}

In response data, we get a score and some other values like below response data.

{
  "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
  "score": number             // the score for this request (0.0 - 1.0)
  "action": string            // the action name for this request (important to verify)
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

Let me explain this response data field one by one. Here, we are getting the following data like:

Success: It may be true or false. If it is true then the next option will be checked otherwise request will be identified as spam or bots request.

Score: It may be between 0.0 to 1.0. If the score is greater than or equal to 0.5 then it will be identified as a human request otherwise it will be identified as a spam request.

Action: This returns the same value of action which was sent at the time of token generation. This is very helpful to verify that your response data is real or not. If your response data is real (that means not changed by anyone in between reCAPTCHA verify) then requested action value and response action value will be the same.

Challenge_ts: This is the timestamp when your reCAPTCHA challenge loaded.

Hostname: This returns the web URL where the reCAPTCHA request solved.

At the last in the server-side integration, I have written an if condition. If the condition successfully verified then it will be identified as a human otherwise it will be identified as a robot.

Final words for this tutorial

Google always provides a better solution to make everything simple. To prevent spam requests, Google provides a reCAPTCHA API which helps the user to prevent requests sent by computer or robot.

Google reCAPTCHA v3 is the best tool to prevent spam requests because there is no need for user interaction to prevent the robot’s request that’s why the user will not be irritated. For complete details follow this link: Click here for details

Leave a Comment

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

18 Comments

  • Hi Sumit, thanks for this tutorial. Unfortunately, I do not know PHP nor am I well experienced in other languages.
    At the moment, I am sending the form inputs via script as an email like this:

    After replacing the value of the action attribute, I wonder how to trigger the FormMail.cgi. Could you explain this?
    If yes, I would be very thankful.
    Best regards from Switzerland
    Patrick

    • Hi Patrick,

      First of all, thank you for being the first commenter.

      First of all, you need to tell which programming language you are using?

      In every programming language like PHP, when you write action attribute in form tag then it directly submits the form to the action attribute URL. You can receive form data on the action page according to programming language code.

      Thank you.

  • Hi Sumit, thanks for the tutorial. Everything is working fine. This is one of the few tutorials showing how to send POST requests instead of GET. Keep on writing.

  • Hi Sumit,

    Thanks for your tutorial. I tried with php7.2 on win10. I used the test link like “http://localhost:8000/index.php”. But I didn’t see pics and I got an empty $curlResponse back. do u know what the problem could be?

    Thanks,
    Ray

    • Hi Ray,

      The problem occurs because you won’t have added domain in the Google reCAPTCHA. Check first, you have added proper domain or not in the Google reCAPTCHA website where site key and secret key are generating.

      • Thanks, Sumit. It looks like there is a delay for google to generate token a new domain. When I tried it after the weekend, it works. But I always got score =0, and still no pics at all.

        Ray

    • This tutorial is really good with an explanation. You can also check another article to add Google reCAPTCHA V3 in PHP Ajax contact form with a live demo and can download complete code.
      flamontech. com/google-recaptcha-v3-php-ajax-example-github-link/

  • I’ve tried using this, I ran several tests on 01/18/2020 but I kept getting the “You are not a human” response. I’ve checked the reCaptcha page to see how many failures and they recorded all as successful with a score of 0.9 but the code keeps failing over and I can’t see a reason why. Any Ideas?

    • Hi Andrew,

      I have applied same code on multiple websites and it is working fine. According to your comment, that you are getting 0.9 score it may be that you are doing some conditional mistake.

      Make sure you are writing correct code.

  • Excellent tutorial – I looked at several trying to get reCaptcha v3 to work. Your code is simple and clean and it works. Thank you!

  • This tutorial is really good with an explanation. You can also check another article to add Google reCAPTCHA V3 in PHP Ajax contact form with a live demo and can download complete code.
    flamontech. com/google-recaptcha-v3-php-ajax-example-github-link/