php - 如何在服务器端验证 Google reCAPTCHA v3?

标签 php recaptcha recaptcha-v3

我刚刚使用复选框设置了新的 google recaptcha,它在前端工作正常,但是我不知道如何使用 PHP 在服务器端处理它。我尝试使用下面的旧代码,但即使验证码无效,也会发送表单。

require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
 $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}

最佳答案

私钥安全

虽然这里的答案肯定有效,但它们使用的是 GET 请求,该请求会公开您的私钥(即使使用了 https)。在 Google Developers指定的方法是POST

更多细节:https://stackoverflow.com/a/323286/1680919

通过 POST 验证

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

数组语法: 我使用"new"数组语法([] 而不是 array(..))。如果您的 php 版本尚不支持此功能,则必须相应地编辑这 3 个数组定义(请参阅注释)。

返回值: 如果用户有效,该函数返回true,如果无效则返回falsenull如果发生错误。例如,您可以通过编写 if (isValid()) { ... }

来使用它

关于php - 如何在服务器端验证 Google reCAPTCHA v3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27274157/

相关文章:

php - Codeigniter 表单验证集消息

php - Google reCaptcha 2.0 不工作,是否用于 curl ?

open-source - 开源隐形 reCAPTCHA 替代品

asp.net-mvc - 我该如何处理 reCAPTCHA v3 中的低分?

构造函数中不存在 PHP 类

php - Codeigniter:foreach 方法或结果数组?? [模型+ View ]

php - 使用 PDO 和 MySql 代替 mysqli

c# - 如何在运行时设置 recaptcha key 设置

python - 在 Django 中验证 reCAPTCHA v3

recaptcha - 谷歌 reCAPTCHA 在中国