file_get_contents和错误代码

时间:2011-11-20 20:45:24

标签: http header http-status-code-404 file-get-contents

我正在使用file_get_contents从网上下载文件。 有时我会 503服务不可用 404 Not Found

  

警告:file_get_contents(http://somewhereoverinternets.com)   [function.file-get-contents]:无法打开流:HTTP请求   失败! HTTP / 1.0 503 Service在somesourcefile.php中不可用   20

如何获取此错误代码 - 503? 404,200? 为这些案件制定程序。

2 个答案:

答案 0 :(得分:34)

使用file_get_contents时,您实际上可以获得所需的标头。这些头文件在PHP $http_response_header中可用,PHP在全局范围内创建。

例如,以下代码(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"
}

答案 1 :(得分:6)

请尝试使用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);
}
相关问题