Home > Article > Backend Development > How to Validate Google reCAPTCHA v3 on the Server Side with PHP?
Background:
Google reCAPTCHA v3 is an enhanced version of the popular CAPTCHA system used to prevent spam and abuse. It relies on machine learning models to analyze user behavior and provides a risk analysis score rather than a simple challenge-response mechanism.
Server-Side Validation:
To validate reCAPTCHA v3 on the server side using PHP, you need to perform the following steps:
Retrieve POST Data:
Set Request Parameters:
Prepare HTTP Request:
Execute Request:
Parse Response:
Validate reCAPTCHA:
Example Code:
<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:
Simply call the isValid() function to validate the reCAPTCHA token received from the client side.
<code class="php">if (isValid()) { // User passed reCAPTCHA } else { // User failed reCAPTCHA }</code>
The above is the detailed content of How to Validate Google reCAPTCHA v3 on the Server Side with PHP?. For more information, please follow other related articles on the PHP Chinese website!