gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:57:56 24 4
gpt4 key购买 nike

我刚刚使用复选框设置了新的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com