


How to Validate Google reCAPTCHA v3 on the Server Side with PHP?
Nov 01, 2024 am 09:44 AMValidating 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:
-
Retrieve POST Data:
- Extract the 'g-recaptcha-response' value from the POST data received from the client-side form submission.
-
Set Request Parameters:
- Specify your secret key, the 'g-recaptcha-response' value, and the client's IP address in an array.
-
Prepare HTTP Request:
- Create an HTTP context with the specified request method, headers, and POST data.
-
Execute Request:
- Use file_get_contents() with the HTTP context to send the request to reCAPTCHA's API.
-
Parse Response:
- Decode the JSON response received from reCAPTCHA and extract the 'success' parameter.
-
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
