如何修复常见 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 (将#修改为@)