reCAPTCHA 总是验证失败

reCAPTCHA always fails to validate

我有以下用于 Google 重新验证的函数:

function isNotSpam(){
    if(isset($_POST['g-recaptcha-response'])){
        try {
            $url = 'https://www.google.com/recaptcha/api/siteverify';
            $data = ['secret'   => $google_captcha_secert,
                     '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;}
    }else{return null;}
}

然后我这样检查错误:

    $google_captcha_secert = "/my secret key here/";
    if(!isNotSpam()){display error here}

我的 HTML 包含以下 reCAPTCHA

代码
<script src="https://www.google.com/recaptcha/api.js?hl=en"></script>
</head>
<body>
...
<form>
...
<div class="g-recaptcha" data-sitekey="/ my public key here /"></div>
...
</form>
</body>

我做错了什么?我尝试通过使用不带 !function 的函数来检查错误,并改为以这种方式使用它:

if(isNotSpam()){}else{display error here}

我试着用

if(isNotSpam() == null){display error here}

什么都不行,它总是告诉我我是机器人,但这显然是不正确的。能告诉我错在哪里吗?

$google_captcha_secert 未在您的函数内定义,因为您既未使用 global keyword 从全局范围导入它,也未将其作为参数提供给您的函数。

可能还有更多错误,考虑记录错误响应/异常,而不是静静地吞下它们以便能够自己调试此类问题。我还建议在调试时启用 error_reporting。 PHP 应该在那里打印通知。