Example of How to Add Google reCAPTCHA v3 to a PHP Form

In this article, I’m going show you how to add Google reCAPTCHA v3 to a form on your PHP website. The latest reCAPTCHA is different than the previous versions—it doesn’t require user interaction at all. In this post, we’ll see how it works, and we’ll build a real-world example for demonstration purposes.

As a website owner, you’re always looking for a strong anti-spam solution which can prevent spamming on your website and only allows legitimate content to come through. Gone are the days when you could integrate a simple text-based CAPTCHA solution and it was enough to stop the naughty bots.

On the other hand, if you have used third-party anti-spam solutions for your website, it’s likely that you’re aware of the reCAPTCHA solution provided by Google. With each version of reCAPTCHA, Google has strengthened its capabilities to detect and filter out spam. Specifically, reCAPTCHA v2 is one of the best among the different third-party anti-spam solutions.

You can integrate reCAPTCHA v2 on your website in two different ways. The first is the famous “I’m not a robot” checkbox. And the other one is the invisible method in that the user interaction is required only in suspicious cases. In this post, we’ll discuss reCAPTCHA v3, which is invisible and doesn’t require user interaction at all!

In the next section, I’ll explain how reCAPTCHA v3 works, and later on we’ll build a real-world example to demonstrate it.

How Google reCAPTCHA v3 Works

It’s said that a picture is worth a thousand words! So let’s have a look at the following screenshot to understand what exactly is going on underneath when you integrate reCAPTCHA v3 on your website.

reCAPTCHA Flow

Let’s try to understand the overall flow in detail:

  1. The end user requests a web page.
  2. The web app or server returns the requested page, which includes reCAPTCHA v3 code.
  3. Next, the user fills in the form and clicks on the submit button.
  4. Before submitting the form data to the server, the reCAPTCHA v3 code on the client makes an AJAX call to the Google server and obtains a token. The important thing here is that we have to pass the action attribute with an appropriate value during the AJAX call. You should pass the value which identifies your form. This is the value which you’ll use for verification on the server side, along with other parameters.
  5. The token obtained in the previous step is submitted along with the other form data. In most cases, we append two hidden variables to the form, token and action, before the form is submitted.
  6. Once the form is submitted, we have to perform the verification step to decide if the form is submitted by a human. As a first step, we’ll make a POST request to verify the response token. The POST request passes the token along with the Google secret to the Google server.
  7. The response is a JSON object, and we’ll use it to decide if the form is submitted by a human. The format of the JSON object is shown in the following snippet.

There are three checks that we must do to make sure that it’s safe to go ahead with processing the form. The response score should be greater than 0.5, and the success property should be TRUE. Along with that, you must compare the response action value with the value of the action hidden variable which is submitted along with the form.

The reCAPTCHA v3 API returns a certain score for each request without user friction. The response score which you get is based on the user’s interactions with your site—their key presses and mouse movements. The reCAPTCHA v3 learns by the real traffic on your website. So it may be that the scores are different in different environments. As a starting point, you can use a threshold of 0.5, and you could adjust it later on as per your requirements.

So that’s an overview of the process. In the next section, we’ll see how to register your site with Google to get a site key and site secret.

Register reCAPTCHA v3 Key and Secret

The Google reCAPTCHA library requires you to register keys for your domain before you can actually use it. In this section, we’ll see how you can register it.

First, go to the reCAPTCHA admin panel to create a link which presents you with a form asking you for a few details, as shown in the following screenshot.

reCAPTCHA Admin Panel: Register Your Website

In the reCAPTCHA Type field, select the reCAPTCHA v3 option. Fill in the Domains and Owners information as needed. Next, read and accept the reCAPTCHA Terms of Service. Finally, click on the Submit button to save the settings.

Upon form submission, Google generates a site key and site secret for your domain, as shown in the following screenshot.

reCAPTCHA admin panel: Copy Keys

Please copy and note these down as we’ll need them later on when we build our real-world example.

Build a Real-World Example

In the previous section, we created the necessary credentials which we could use while setting up the reCAPTCHA v3. In this section, we’ll create an example to demonstrate how to integrate it in your PHP web page.

We’ll create two PHP files: subscribe_newsletter_form.php and subscribe_newsletter_submit.php.

  • The subscribe_newsletter_form.php file is used to display the newsletter subscribe form, which allows the user to enter the email address and subscribe for newsletters.
  • The subscribe_newsletter_submit.php file handles the form submission and does the necessary validation.

Create the Newsletter Subscribe Form

Go ahead and create the subscribe_newsletter_form.php file with the following contents.

Let’s go through the important snippets in this file.

First, we loaded the reCAPTCHA JavaScript library in the <head> section. It’s important to note that you have to pass your site key as a render=YOUR_SITE_KEY query string parameter. Also, we’ve loaded the jQuery library as well so that we can use form-related utility methods. It’s not necessary to use jQuery—you can use any other library of your choice, or even vanilla JavaScript.

Next, we created a basic form which includes the email textbox and submit button—nothing fancy here.

Finally, there’s the JavaScript snippet at the end of the file, which is the key part for implementing reCAPTCHA. We’ve created the jQuery submit handler for the form so that when the user submits the form, we catch that event and do the necessary processing before the actual form submission. We use the event.preventDefault() function to stop the form submission from taking place when it normally would.

Next, the grecaptcha object calls the execute method, which obtains the token from the Google server by performing an AJAX call. It’s important to note that you have to pass the site key and action name while calling the execute method. The action name allows you to have a detailed break-down of data in the Google admin console. It’s also used to verify the reCAPTCHA response on the server side, which we’ll see a bit later.

When the execute method receives the token response, it passes the token to the anonymous function supplied in the then method. Next, we append two new hidden variables to the form, token and action, along with their values. Finally, we submit the form by calling the submit method of jQuery.

Handle Form Submission and Validation

Go ahead and create the subscribe_newsletter_submit.php file with the following code to handle form submission.

The most important part after form submission is to verify the token which is submitted along with the other form values. For that, you need to make a POST request to the https://www.google.com/recaptcha/api/siteverify URL. Also, you need to pass the secret key and token as the POST data. In the above example, we’ve used PHP cURL functions to make the POST request.

As a response, you’ll get a JSON object which contains the necessary information that you can use to verify. As discussed earlier, you should at least check three things to make sure the form is submitted by a human: success, action, and score.

How to Use the reCAPTCHA PHP Client Library

In the previous section, we discussed how you can handle form submission and validation in the subscribe_newsletter_submit.php file. In this file, we’ve used the core PHP code to call the Google API and verify the response from the Google server. Although it’s useful to understand the underlying flow, usually you’ll want to just use a ready-made library so you don’t have to rewrite this commonly-used code.

In this section, I’ll show you how to use the reCAPTCHA PHP client library to handle form submission and validation.

Go ahead and run the following command from your project directory to install the reCAPTCHA PHP client library.

Once it’s installed, you just need to include the autoload.php file as shown in the following snippet.

In our example, let’s revisit the subscribe_newsletter_submit.php file to make necessary changes.

As you can see, we’ve instantiated the ReCaptchaReCaptcha class which is provided by the reCAPTCHA client library.

Next, we’ve called a couple of methods like setExpectedAction and setScoreThreshold to set the incoming action and expected score values. Finally, we’ve to call the verify method to check if the $token variable holds a valid value.

The verify method returns an object which we can use to check if the verification went through successfully, As you can see, we’ve used the isSuccess method to check it. If the verification was not successful, you can use the getErrorCodes method to retrieve errors and act accordingly.

As you can see, it’s fairly straightforward to use the reCAPTCHA client library to validate the Google reCAPTCHA v3.

This makes it easy to use Google reCAPTCHA v3 in your PHP web pages to detect and prevent spamming.

Conclusion

Today, we discussed how you can use one of the most popular anti-spam solutions on the web: Google reCAPTCHA v3. We created a real-world example to demonstrate how you can integrate it in a PHP website.

Check out some of the other free PHP tutorials we have on offer!

Leave a comment

Your email address will not be published.