我正在使用google recaptcha在我的网站查询表格中。我使用了 cURL 而不是 file_get_contents()
,因为我的服务器的 allow_url_fopen 由于安全问题而被禁用。这是我验证验证码的代码:
<?php
$response=htmlspecialchars($_POST["captcha"]);
$secret = "my_secret_key";
$curl = curl_init();
$captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";
curl_setopt($curl, CURLOPT_URL,$captcha_verify_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=".$secret."&response=".$response);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$captcha_output = curl_exec ($curl);
curl_close ($curl);
$decoded_captcha = json_decode($captcha_output);
$captcha_status = $decoded_captcha['success']; // store validation result to a variable.
if($captcha_status === FALSE){
echo "fail";
}
else
{
echo "success";
}
?>
我的问题是,当我检查 recaptcha 时,如果我将 google url 更改为任何内容或将我的 key 更改为任何内容,我会得到成功的响应。如果 key 不正确,它不应该返回成功,对吧?即使我改变google_verify_url我得到成功的回应。我不明白发生了什么事。我这边有什么问题吗?
最佳答案
当您发送带有错误参数的请求时,curl 的响应将为 NULL
而不是 FALSE
,这就是为什么它总是返回 success
。此外,您还会收到一个警告,因为您将对象用作数组。这应该有效:
$response = htmlspecialchars($_POST["captcha"]);
$secret = "my_secret_key";
$curl = curl_init();
$captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";
curl_setopt($curl, CURLOPT_URL, $captcha_verify_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=".$secret."&response=".$response);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$captcha_output = curl_exec($curl);
curl_close ($curl);
$decoded_captcha = json_decode($captcha_output, TRUE); // Changed the second parameter
$captcha_status = $decoded_captcha['success'];
if($captcha_status == NULL){ // Changed False to Null
echo "fail";
} else {
echo "success";
}
关于php - 使用 PHP 的 google recapcha 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806599/