使用PHP的Google Recpatcha问题

时间:2018-08-12 07:14:07

标签: php curl recaptcha

我正在网站查询表单中使用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更改为任何内容或将我的秘密密钥更改为任何内容,我都将获得成功的响应。如果密钥不正确,它不应该返回成功吗?即使更改google_verify_url,我也会收到成功响应。我不明白发生了什么。我这边有什么问题吗?

2 个答案:

答案 0 :(得分:2)

当您发送带有错误参数的请求时,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";
 }

答案 1 :(得分:0)

http://php.net/manual/en/function.json-decode.php

  

assoc为TRUE时,返回的对象将转换为关联对象   数组。

$decoded_captcha = json_decode($captcha_output, true);

更好地捕获异常:

try {
 ......
} catch (Throwable $exception) {
   echo $exception;
}