cURL 有时不起作用并给出空结果

问题描述 投票:0回答:6

我使用 cURL 从另一个网站获取数据。有时显示数据,有时显示空结果

这是我的代码


    函数 get_data($url) {
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        $agent=$_SERVER["HTTP_USER_AGENT"];
        curl_setopt($ch,CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);

        $数据=curl_exec($ch);
        卷曲_关闭($ch);
        返回$数据;
    }
    $returned_content = get_data('www.example.com');
    回显 $returned_content;

php curl php-curl
6个回答
4
投票

可能是你从curl_init调用了太多的连接到一个IP地址,所以服务器阻塞了连接并导致开/关错误。


3
投票

未收到任何内容可能是由于多种不同原因中的一个或多个原因造成的,您需要弄清楚是哪一个原因。

  1. 执行传输后,在代码中使用

    curl_error($ch)
    查看curl 是否告诉您问题。

  2. 调查响应标头。 HTTP 传输可以成功且不返回任何错误,但可能仅响应 HTTP 标头而根本不响应正文。然后,HTTP 标头可能包含有关原因的线索。也许这是您应该遵循的重定向,也许它需要 HTTP 身份验证,或者服务器可能指示临时服务器故障。


0
投票

PHP 中的 Curl 在 AWS EC2 实例上返回 null

我有类似的问题,我通过确保 PHP5 和 Apache2 文件夹中的 php.ini 文件中的版本和设置相同来修复它。如果不是,那么 Apache2 会尝试执行 php.ini 设置中设置的版本。还要确保安装了 PHP5-libcurl。也很重要。


0
投票

间歇性故障可能是由于不稳定的 DNS 服务器造成的,即使不是,您仍然会从使用 Google 的 DNS 服务器中受益。 请参阅:https://developers.google.com/speed/public-dns/docs/using


0
投票

解决方案

确保您的变量或网址中没有空间。就像“$user_name =“Lokman Hosen””。您必须提供 urldecode "$user_name = "Lokman_Hosen"" 或 "$user_name = "Lokman%20Hosen""。你可以用

urldecode()

去除空格功能。现在 cURL 不允许任何空格。


0
投票

我在尝试连续多次连接到 API 时遇到了这个问题。

我的答案与@developer几乎相同:

可能您从一个IP地址调用了太多连接,因此服务器阻止了连接并导致开/关错误。

这对我来说是一种解决方法。

创建一个尝试多次curl请求的方法,在每个请求之间添加时间,直到获取数据或放弃。

/**
 * Thanks to issues with sometimes not receiving data when making multiple requests
 * here we make a reasonable effort to get data even when a firewall or WAF or ?? maybe
 * throttling request, DDOS, or on fire
 *
 * @param Curl $ch
 *
 * @return bool|string
 */
function curlExecFireWalker($ch)
{
   //In case we fail, let's count our failures
   $wowFailCount = 0;
   do {
      $data = curl_exec($ch);
      if (!$data) {
         //Well this is awkward, we are expecting data and didn't get any :(
         $wowFailCount++;
         //Let's calculate the length of a smoke break
         $smokeBreak = pow($wowFailCount, 2);
         //Smoke 'em if you got 'em
         sleep($smokeBreak);
      }
      //Well let's not allow to many failures and get out of here before the entire thing is on fire
   } while (!$data && $wowFailCount <= 3);

   return $data;

}

然后代替

$data = curl_exec($ch);

调用走火者方法

$data = curlExecFireWalker($ch);

© www.soinside.com 2019 - 2024. All rights reserved.