【问题标题】:Issue with google recpatcha using PHP使用 PHP 的 google recaptcha 问题
【发布时间】:2018-08-12 07:14:07
【问题描述】:

我在我的网站查询表中使用google recaptcha。我使用 cURL 而不是 file_get_contents(),因为我的服务器的 allow_url_fopen 由于安全问题而被禁用。这是我验证recaptcha的代码:

        <?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,我也会得到成功响应。我无法理解发生了什么。我这边有什么问题吗?

【问题讨论】:

    标签: php curl recaptcha


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      $decoded_captcha = json_decode($captcha_output, true);
      

      更好地捕捉异常:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-02
        • 1970-01-01
        • 2018-09-13
        • 1970-01-01
        • 2016-08-26
        • 2020-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多