如何解决如何修复常见 php 表单上的 recaptcha v3 重新加载错误?
我的入口点是这个 php 文件(称为“form.php”):
<?php require_once 'controller.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://www.google.com/recaptcha/api.js?render=MYKEY"></script>
</head>
<body>
<h1>Form</h1>
<h3>Protected by RecaptchaV3</h3>
<form onsubmit="event.preventDefault(); handleForm();" id="form" action="form.php" method="POST">
<input type="text" value="<?php echo $username; ?>" name="username">
<input type="hidden" name="recaptchaResponse" id="recaptchaResponse">
<button type="submit" name="submit-btn">Submit</button>
</form>
<script>
function handleForm() {
grecaptcha
.execute("MYKEY",{
action: "submit",})
.then(function(token) {
var recaptchaResponse = document.getElementById("recaptchaResponse");
recaptchaResponse.value = token;
console.log("New token: " + token);
var form = document.getElementById("form");
form.submit();
});
}
</script>
</body>
</html>
它基本上是一个简单的表单,其中一个用于用户用户名的文本输入和一个用于 recaptcha v3 的隐藏输入。 服务器端表单验证和 recaptcha 检查发生在“controller.php”中:
<?php
$username = "";
if ($_POST) {
$username = $_POST["username"];
// RECAPTCHA VERIFICATION
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => 'MYSECRET','response' => $_POST["recaptchaResponse"]
);
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n","Content-Length: " . strlen($query) . "\r\n" . "User-Agent:MyAgent/1.0\r\n",'method' => 'POST','content' => $query
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url,false,$context);
echo print_r($verify,true);
$captchaResponse = json_decode($verify);
$verificationSuccess = false;
if ($captchaResponse->success && $captchaResponse->score > 0.5) {
$verificationSuccess = true;
}
if (!empty($username)) {
if ($verificationSuccess) {
header("location: success.php");
} else {
echo "<br>Captcha failed.";
}
} else {
echo "<br>Invalid username.";
if (!$verificationSuccess) {
echo "<br>Captcha failed.";
}
}
}
这通常效果很好,正如您在以下动画 gif 中看到的:https://tenor.com/view/gif-20982958
但是如果我的输入无效然后我重新加载页面,则会发生以下错误(每次!):https://tenor.com/bAcN4.gif
在过去的三个小时内,我阅读了很多关于此错误的信息(例如,此处:I got "timeout-or-duplicate" error using ReCaptcha v3 或此处:https://developers.google.com/recaptcha/docs/verify)。问题在于令牌,由于重新加载,它使用了两次。但不幸的是,我在任何地方都没有找到适合我的正确解决方案。所以我被迫在这里问我自己的问题。 我希望你能帮助我...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。