Home > Article > Backend Development > How to Verify Google reCAPTCHA v3 on the Server Side in PHP?
Problem: You've implemented Google reCAPTCHA v3 with a checkbox on the front end, but you're facing difficulties validating it on the server side. The form is being submitted even when the captcha is invalid.
Solution:
To effectively handle Google reCAPTCHA v3 validation on the server side, it's crucial to use POST requests. Here's a solution:
<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>
Explanation:
Usage:
In your code, simply write:
if (isValid()) { // The user has passed the captcha validation. } else { // The user has failed the captcha validation. }
Note: Ensure to replace [YOUR SECRET KEY] with your actual reCAPTCHA secret key in the provided code snippet.
The above is the detailed content of How to Verify Google reCAPTCHA v3 on the Server Side in PHP?. For more information, please follow other related articles on the PHP Chinese website!