Home  >  Article  >  Backend Development  >  How to Verify Google reCAPTCHA v3 on the Server Side with PHP?

How to Verify Google reCAPTCHA v3 on the Server Side with PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 05:10:27481browse

How to Verify Google reCAPTCHA v3 on the Server Side with PHP?

Verifying Google reCAPTCHA v3 on the Server Side with PHP

The new Google reCAPTCHA checkbox seamlessly integrates into the front end, but its server-side handling using PHP might pose challenges. To effectively process it on the server, it's crucial to understand the key differences from the previous reCAPTCHA versions.

Old reCAPTCHA Validation

The provided code snippet from the question demonstrates an approach used for earlier reCAPTCHA versions. However, it's not suitable for reCAPTCHA v3:

<code class="php">require_once('recaptchalib.php');
// ...
if (!$resp->is_valid) {
  $errCapt = '<p style="color:#D6012C ">The CAPTCHA Code was not entered correctly.</p>';
}</code>

Security Considerations

It's worth noting that the GET request method used in the given solution exposes your private key. For enhanced security, Google recommends using a POST request instead.

Verifying reCAPTCHA v3 via POST

To successfully validate reCAPTCHA v3 on the server side using PHP, follow these steps:

<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>

This function will return true if the user has successfully passed the reCAPTCHA test, false otherwise, and null in case of an error. By using this function, you can efficiently authenticate users and mitigate spam and bot activity.

The above is the detailed content of How to Verify Google reCAPTCHA v3 on the Server Side with PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn