How to validate Google reCAPTCHA v3 on server side?

To validate a Google reCAPTCHA v3 on the server side using PHP, you will need to do the following steps:

  1. Install the GuzzleHTTP library, which allows you to make HTTP requests from PHP: composer require guzzlehttp/guzzle
  2. On your HTML form, add the reCAPTCHA v3 widget by including the following script:
<script src='https://www.google.com/recaptcha/api.js?render=SITE_KEY'></script>
  1. In your form's JavaScript, execute the reCAPTCHA v3 widget, and get the token:
grecaptcha.ready(function() {
    grecaptcha.execute('SITE_KEY', {action: 'action_name'}).then(function(token) {
        document.getElementById('g-recaptcha-response').value = token;
    });
});

Watch a course Learn object oriented PHP

  1. On your PHP script, use the GuzzleHTTP library to make a POST request to the reCAPTCHA API, passing along your SECRET_KEY and the token from the previous step:
$client = new GuzzleHttp\Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
    'form_params' => [
        'secret' => 'SECRET_KEY',
        'response' => $token
    ]
]);
  1. Decode the JSON response from the API and check whether the validation was successful:
<?php

$result = json_decode($response->getBody());
if ($result->success) {
    // validation was successful
} else {
    // validation was unsuccessful
}

Note: You will need to replace SITE_KEY and SECRET_KEY with the appropriate values for your site.