file_get_contents和错误码

6
我正在使用file_get_contents从网站下载文件。有时会出现503 Service Unavailable404 Not Found的错误。

警告: file_get_contents(http://somewhereoverinternets.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable in somesourcefile.php on line 20

我该如何获取这些错误代码 - 503?404, 200? 以便对这些情况进行处理。

请查看此链接:https://dev59.com/TW855IYBdhLWcg3waDiR#4358136 - sugresmax
2个回答

40

使用 file_get_contents 函数时,你实际上可以获取所需的头信息。这些头信息被存储在 PHP 创建的全局数组 $http_response_header 中。

例如,以下代码(其中 URI 指向本地服务器上不存在的资源):

$contents = @file_get_contents('http://example.com/inexistent');
var_dump($http_response_header);

得到以下结果:

array(8) {
  [0]=>
  string(22) "HTTP/1.1 404 Not Found"
  [1]=>
  string(22) "Cache-Control: private"
  [2]=>
  string(38) "Content-Type: text/html; charset=utf-8"
  [3]=>
  string(25) "Server: Microsoft-IIS/7.0"
  [4]=>
  string(21) "X-Powered-By: ASP.NET"
  [5]=>
  string(35) "Date: Thu, 28 Mar 2013 15:30:03 GMT"
  [6]=>
  string(17) "Connection: close"
  [7]=>
  string(20) "Content-Length: 5430"
}

7

建议使用curl代替:

function get_data($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);

  if(!curl_errno($ch)){ 
     return $data;
  }else{
    echo 'Curl error: ' . curl_error($ch); 
  }
curl_close($ch);
}

只用curl?呵呵,用file_get_contents很容易啊。不管怎样,感谢你的回答。 - ABTOMAT
嗨@Al-Punk - 在这个例子中,使用curl相比file_get_contents有什么好处呢?(一般来说,显然curl更加健壮。) - itarato
@itarato file_get_contents 是一个简单的方法,可以完成工作。cURL 有很多选项来优化您的请求。将 file_get_contents 视为公共交通工具,它将带您去某个地方,将 curl 视为一辆法拉利,它速度更快,在旅途中会给您带来更多的乐趣。 - Al-Punk
谢谢@Al-Punk,我一直在想可能有什么不同。也许它有不同的超时时间、请求头等。非常感谢;) - itarato
1
@Al-Punk,你有关于Curl更快的声明的任何参考资料吗? - e-sushi
做了一个快速搜索:https://dev59.com/Dmgu5IYBdhLWcg3wzKEc#37256025我以前也进行过多次测试,但没有可呈现的基准。 - Al-Punk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接