How to protect your website against spam with Google reCAPTCHA V3 or V2 [PHP + Extension WordPress]

We will see how to use Google reCAPTCHA V3 and V2 to protect a website against spam through this article. The goal of our article will be to see how to add a captcha to a form. We will also see how the Captcha V3 works. Finally, we will discuss the types of captcha and why V3 is better than other versions.

Prerequisites for the tutorial version of the article

  • For everyone  – If you are a curious reader, you can read this article for general knowledge. We have a free plugin available for WordPress websites which you can download from wordpress.org
  • An option for developers – However, if you are a developer and would like to apply our advice on your project, you must have the

A developer will need:

  • Basic knowledge of HTML.
  • Some notions in PHP.
  • Knowing JavaScript could be a plus.

Protect your website against spam with Google reCAPTCHA V3 in just 3 steps

To protect your website with Google reCAPTCHA V3, you only have to follow a few steps. In this part, we will see the different steps to follow.

recaptcha

Step 1 – Registering your website on the Google reCAPTCHA platform

To use Google reCAPTCHA V3, you must first register your site on the Google reCAPTCHA platform. Please note that it should be published on the net to register a site. Here are the steps to follow:

  • Visit the site Google reCAPTCHA – and click on the admin console. The site will redirect you to the login page.
  • If you have a Gmail or G-Suite account, you must log in to access the Captchas management panel. Otherwise, you need to create a Gmail account.
  • Click on the plus in the upper right corner of the admin panel, and a website registration form will appear.
  • Via this form, you must enter the name of your site, the type of reCAPTCHA and the domain names (
  • After saving the form, the platform will generate a site key and a secret key. Copy the keys for the following steps.

Step 2 – Adding parameters to the form and managing data on the client-side.

We will use an HTML contact form for illustration. Please note that you may be able to add catcha on any type of form.

Addition of hidden fields on the contact form

We’ll add a hidden field called “reponsecaptcha” on our HTML contact form. This field aims to detect whether the user is a human or a robot.

Here’s what the code for the initial form might look like.


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Envoyer un message</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>

<div class="container">
  <h2>Send an SMS</h2>
  <form action="envoyer.php" method="POST">
    <div class="form-group">
      <label for="email">Nom et Prénom</label>
      <input type="tel" class="form-control"  placeholder="Nom et Prénom" name="firstlastname">
    </div>
    <div class="form-group">
      <label for="pwd">Email</label>
      <input type="email" class="form-control"  placeholder="Adresse Courriel" name="youremail">
    </div>
    <div class="form-group">
      <label>
         Votre Message
      </label>
      <textarea  class="form-control" placeholder="your message" name="yourmessage"></textarea>
    </div>
    <button type="submit" class="btn btn-primary form-control">Envoyer le message</button>
  </form>
</div>
</body>
</html>

Code 1 – Initial code without the captcha field

After adding the hidden field and other parameters, we will have a form similar to the one below


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Envoyer un message</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>

<div class="container">
  <h2>Send an SMS</h2>
  <form action="envoyer.php" method="POST">
    <div class="form-group">
      <label for="email">Nom et Prénom</label>
      <input type="tel" class="form-control"  placeholder="Nom et Prénom" name="firstlastname">
    </div>
    <div class="form-group">
      <label for="pwd">Email</label>
      <input type="email" class="form-control"  placeholder="Adresse Courriel" name="youremail">
    </div>
    <div class="form-group">
      <label>
         Votre Message
      </label>
      <textarea  class="form-control" placeholder="your message" name="yourmessage"></textarea>
    </div>
     <input type="hidden" name="reponsecaptcha" id="recaptcha">

    <button type="submit" class="btn btn-primary form-control" name="envoie">Envoyer le message</button>
  </form>
</div>
<script src="https://www.google.com/recaptcha/api.js?render=LA_CLE_DE_VOTRE_SITE"></script>
    <script>
        grecaptcha.ready(function () {
            grecaptcha.execute('LA_CLE_DE_VOTRE_SITE', { action: 'contact' }).then(function (token) {
                var recaptchaResponse = document.getElementById('recaptcha');
                recaptchaResponse.value = token;
            });
        });
    </script>
</body>
</html>

Code 2 – Final code with the captcha field v3

Code comments

  • If you pay attention to Codes 1 and 2, you will realize that we have added a hidden field to line 28 of code 2. We also added JavaScript code from line 33.
  • To activate reCAPTCHA V3 on your site, you must replace LA_CLE_DE_VOTRE_SITE with the key obtained in step 1.
  • On line 36, you will notice a parameter called “action:” You can vary this parameter according to your objectives. The action is the name of the action you would like to perform. To learn more about the different options available to you, please refer to the documentation for the other options.

If you could follow the instructions, you should see the Google reCAPTCHA V3 icon appear on your site in the bottom right corner of your site. It simply means that the captcha is activated but not yet functional. We look at the next step, managing the sending of information.

Step 3 – Managing Server-Side Information

Managing data on the server side will simply consist of:

  • retrieve the information sent by the user,
  • check if its score is above average (usually 0.5)
  • Block the sending of the message when it seems suspicious.

Creation of the data reception file — send.php

We will create a PHP file that will allow us to retrieve the data submitted by the user. The file could have information similar to the data below:


<?php // Vérifier si le formulaire a été soumis
if(isset($_POST['envoie']) && isset($_POST['reponsecaptcha'])) {

    // Connecter à Google avec les clés
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = 'VOTRE_CLE_SECRETE';
    $recaptcha_response = $_POST['reponsecaptcha'];

    // Décoder les informations récupérées
    $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
    $recaptcha = json_decode($recaptcha);

    // Effectuer une action en fonction du score obtenu.
    if ($recaptcha->score >= 0.5) {
        // Envoyer le couriel
    } else {
        // Vous n'avez pas vérifier si l'utilisateur est un humain ou un robot. Affichez le message d'erreur.
    }

} ?>

Note

Please note that the PHP code uses the file_get_contents function. Some server does not support file_get_contents for security reasons. In this case, we highly recommend you use CURL. By replacing file_get_contents with CURL, the above code will become:


<?php // Vérifier si le formulaire a été soumis
if(isset($_POST['envoie']) && isset($_POST['reponsecaptcha'])) {

    // Connecter à Google avec les clés
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = 'VOTRE_CLE_SECRETE';
    $recaptcha_response = $_POST['reponsecaptcha'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$recaptcha_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => $recaptcha_secret, 'response' => $recaptcha_response)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$capcharespo = curl_exec($ch);
curl_close($ch);
$Reponse = json_decode($capcharespo, true);

    // Effectuer une action en fonction du score obtenu.
    if ($Reponse['score'] >= 0.5) {
        // Envoyer le couriel
    } else {
        // Vous n'avez pas vérifier si l'utilisateur est un humain ou un robot. Afficher le message d'erreur.
    }

} ?>

Other Alternatives –  use of Google reCAPTCHA V2

Version 2 offers a checkbox to validate if a user is a robot or physically present on your website. In the event that you prefer version 2, here is the simple procedure to follow:

  1. Register your website
  2. Data management on the client-side.
  3. Server-side information management

The main difference between Google reCAPTCHA V2 and V3 is in the approach. Indeed, reCAPTCHA V2 performs a test with images to be identified and version 3 uses a score.

In the following, we will see the adjustments in version 2.

Add an HTML field containing the public key in your HTML form

In the lines of code below, we illustrate what your code should look like.  It is crucial to notice the line with the code below.

<div class="g-recaptcha" data-sitekey="VOTRE_CLE_PUBLIC"></div>

Your final code should look like this:

Then include Google JavaScript, which will take care of the validations.

Note: We have not gone back to site registration or key creation. To include your reCAPTCHA V2 keys, you must select version 2 when creating the keys.

Server-side data management

There is no significant difference in handling versions 2 and 3. For version 3, you need to set an acceptable score for your website. On the other hand, for version 2, if there is a failure, the information returned will be empty.

A comparison between the reCAPTCHA V2 and V3

reCAPTCHA v3 is the latest version suggested by Google to help protect websites from spam emails. Compared to the “I’m not a robot” version, it doesn’t add an extra field to the form. Therefore, this reduces the loss of the number of customers who may not pass the tests.  The “I’m not a robot” version (V2) can sometimes be frustrating if the visitor fails to solve the puzzle for some reason.

Moreover, for some reason, version 3 can be wrong in evaluating the score. One of your visitors might have trouble using your solution if this should happen.

recaptcha v2 and v3

A plugin to add reCAPTCHA V2 or V3 to your WordPress website

We released WordPress extension – reCAPTCHA V2 and V3 for the login page and account creation in the WordPress.org extension bank.

recaptcha plugin

How to use our extension on your website?

The first step will be to download. You could get it either:

  1. Via the WordPress.org website – the recaptcha plugin link
  2. In your WordPress admin panel. – by searching in the extension tab. (Prositeweb)

You will get the code to install manually in the extension tab with the first option. For the second case, after finding the extension, you can follow the standard installation procedure to complete.

Plugin configuration.

L’extension vous donne la possibilité d’utiliser les deux la version 2 et la version 3.  Une fois que vous aurez complété avec l’installation vous devez suivre les étapes suivantes :

  • Click on the Settings – prositecaptcha link
  • In the configuration screen, select the version you want to use
  • Enter your reCAPTCHA keys

If you followed the key generation step correctly, you should have no errors.

Conclusion

Google reCAPTCHA V3 and V2 are great ways to protect websites against spam. Indeed, spam has quite harmful consequences on websites. They can destroy your reputation while causing you to lose money. It is therefore essential to use Captchas to protect your website and your customers’ data.

Thank you for taking the time to read our post. If you have any questions, please leave us a message. You can also contact us if you need help adding a captcha to your website.

Leave a comment



Thank you

Thank you for contacting Prositeweb,
Go back to the home page

Please fill free to contact us at any time for any request regarding our services. Contact us.

Thank you