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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 09:44:43393browse

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

Validating Google reCAPTCHA v3 on the Server Side in 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:

  1. Retrieve POST Data:

    • Extract the 'g-recaptcha-response' value from the POST data received from the client-side form submission.
  2. Set Request Parameters:

    • Specify your secret key, the 'g-recaptcha-response' value, and the client's IP address in an array.
  3. Prepare HTTP Request:

    • Create an HTTP context with the specified request method, headers, and POST data.
  4. Execute Request:

    • Use file_get_contents() with the HTTP context to send the request to reCAPTCHA's API.
  5. Parse Response:

    • Decode the JSON response received from reCAPTCHA and extract the 'success' parameter.
  6. Validate reCAPTCHA:

    • Return 'true' if 'success' is 'true', and 'false' otherwise.

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!

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