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:
To validate a Google reCAPTCHA v3 on the server side using PHP, you will need to do the following steps:
- Install the GuzzleHTTP library, which allows you to make HTTP requests from PHP:
composer require guzzlehttp/guzzle - On your HTML form, add the reCAPTCHA v3 widget by including the following script:
Example of adding the reCAPTCHA v3 on a HTML form
<script src='https://www.google.com/recaptcha/api.js?render=SITE_KEY'></script>
<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">- In your form's JavaScript, execute the reCAPTCHA v3 widget, and get the token:
Example of executing the reCAPTCHA v3 widget, and getting the token
grecaptcha.ready(function() {
grecaptcha.execute('SITE_KEY', {action: 'action_name'}).then(function(token) {
document.getElementById('g-recaptcha-response').value = token;
});
});- On your PHP script, use the GuzzleHTTP library to make a POST request to the reCAPTCHA API, passing along your
SECRET_KEYand the token from the previous step:
Example of using the GuzzleHTTP library to make a POST request to the reCAPTCHA API in PHP
$client = new GuzzleHttp\Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => 'SECRET_KEY',
'response' => $_POST['g-recaptcha-response']
]
]);- Decode the JSON response from the API and check whether the validation was successful:
Example of Decoding the JSON response from the API and checking whether the validation was successful in PHP
<?php
$result = json_decode((string) $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.