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.
Let’s try to understand the overall flow in detail:
- The end user requests a web page.
- The web app or server returns the requested page, which includes reCAPTCHA v3 code.
- Next, the user fills in the form and clicks on the submit button.
- 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.
- 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.
- 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.
- 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.
{ "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 }
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.
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.
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.
<html> <head> <title>Subscribe to Newsletter</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://www.google.com/recaptcha/api.js?render=6LdLk7EUAAAAAEWHuB2tabMmlxQ2-RRTLPHEGe9Y"></script> </head> <body> <div> <b>Subscribe Newsletter</b> </div> <form id="newsletterForm" action="subscribe_newsletter_submit.php" method="post"> <div> <div> <input type="email" id="email" name="email"> </div> <div> <input type="submit" value="submit"> </div> </div> </form> <script> $('#newsletterForm').submit(function(event) { event.preventDefault(); var email = $('#email').val(); grecaptcha.ready(function() { grecaptcha.execute('6LdLk7EUAAAAAEWHuB2tabMmlxQ2-RRTLPHEGe9Y', {action: 'subscribe_newsletter'}).then(function(token) { $('#newsletterForm').prepend('<input type="hidden" name="token" value="' + token + '">'); $('#newsletterForm').prepend('<input type="hidden" name="action" value="subscribe_newsletter">'); $('#newsletterForm').unbind('submit').submit(); });; }); }); </script> </body> </html>
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.
<?php define("RECAPTCHA_V3_SECRET_KEY", 'YOUR_SECRET_HERE'); if (isset($_POST['email']) && $_POST['email']) { $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING); } else { // set error message and redirect back to form... header('location: subscribe_newsletter_form.php'); exit; } $token = $_POST['token']; $action = $_POST['action']; // call curl to POST request $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(array('secret' => RECAPTCHA_V3_SECRET_KEY, 'response' => $token))); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $arrResponse = json_decode($response, true); // verify the response if($arrResponse["success"] == '1' && $arrResponse["action"] == $action && $arrResponse["score"] >= 0.5) { // valid submission // go ahead and do necessary stuff } else { // spam submission // show error message }
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.
$composer require google/recaptcha "^1.2"
Once it's installed, you just need to include the autoload.php file as shown in the following snippet.
require_once '/path/to/recaptcha/src/autoload.php';
In our example, let's revisit the subscribe_newsletter_submit.php file to make necessary changes.
<?php require_once '/path/to/recaptcha/src/autoload.php'; define("RECAPTCHA_V3_SECRET_KEY", 'YOUR_SECRET_HERE'); if (isset($_POST['email']) && $_POST['email']) { $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING); } else { // set error message and redirect back to form... header('location: subscribe_newsletter_form.php'); exit; } $token = $_POST['token']; $action = $_POST['action']; // use the reCAPTCHA PHP client library for validation $recaptcha = new \ReCaptcha\ReCaptcha(RECAPTCHA_V3_SECRET_KEY); $resp = $recaptcha->setExpectedAction($action) ->setScoreThreshold(0.5) ->verify($token, $_SERVER['REMOTE_ADDR']); // verify the response if ($resp->isSuccess()) { // valid submission // go ahead and do necessary stuff } else { // collect errors and display it $errors = $resp->getErrorCodes(); }
As you can see, we've instantiated the \ReCaptcha\ReCaptcha
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!
-
PHPPHP Magic Methods Cheatsheet
-
PHP11 Best PHP Event Calendar and Booking Scripts... and 3 Free Options
-
PHP18 Best Contact Form PHP Scripts for 2021
-
PHP14 Best PHP Help-Desk Scripts and 5 Free Options
-
PHPComparing the 5 Best PHP Form Builders (And 4 Free Scripts)
-
PHP18 Best Contact Form PHP Scripts for 2021
-
PHPCreate a Contact Form in PHP
-
PHP20 Best PHP Email Forms
-
PHPCreate a PHP Email Script and Form
-
PHPCreate a PHP Login Form
-
PHPCreate a Google Login Page in PHP
-
PHPCreate a PHP Contact Form With ContactMe
No comments:
Post a Comment