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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 13:18:02944browse

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

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:

  • The isValid() function is crafted to verify reCAPTCHA v3 using a POST request.
  • It sends the secret key, captcha response, and user's IP address to Google's API.
  • The function parses the API's response and returns true if the captcha is valid, false if it's invalid, and null if an error occurs during the request.

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!

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