Home >Backend Development >PHP Tutorial >How Do I Validate Google reCAPTCHA v3 on the Server Side?
Using Google reCAPTCHA v3 on Server Side
Google's reCAPTCHA v3 is a more advanced method of bot detection compared to its checkbox-based predecessor. While implementing it on the front end is straightforward, handling the validation on the server side requires a different approach.
Deprecated reCAPTCHA v2 Validation
The code you mentioned using for reCAPTCHA v2 validation is no longer suitable for v3. reCAPTCHA v3 uses a POST request with additional parameters and a secret key for validation.
Secure POST-based Validation for reCAPTCHA v3
Here's a revised PHP script using POST-based validation for reCAPTCHA v3:
<code class="php">function isValid() { try { $url = 'https://www.google.com/recaptcha/api/siteverify'; $data = [ 'secret' => '[YOUR SECRET KEY]', 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR'] ]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return json_decode($result)->success; } catch (Exception $e) { return null; } }</code>
Usage
Call the isValid() function to verify the reCAPTCHA token and handle the response accordingly. For example:
<code class="php">if (isValid()) { // The user has passed the reCAPTCHA check. // ... } else { // The user has failed the reCAPTCHA check. // ... }</code>
Security Note
It's essential to use a secret key in the POST request to protect the integrity of the validation. Keep this secret key private and never expose it publicly.
The above is the detailed content of How Do I Validate Google reCAPTCHA v3 on the Server Side?. For more information, please follow other related articles on the PHP Chinese website!