6

I'm downloading a file from the web with file_get_contents. Sometimes I get 503 Service Unavailable or 404 Not Found.

Warning: 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

How can I get this error code - 503 ? 404, 200? To make the process for these cases.

James
  • 2,373
  • 18
  • 16
ABTOMAT
  • 772
  • 4
  • 9
  • 20

2 Answers2

40

You actually can get the headers you want while using file_get_contents. Those headers are available in an array $http_response_header that PHP creates in global scope.

For example the following code (where the URI was pointing to an inexistent resource on a local server):

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

gives the following result:

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"
}
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
7

Try curl instead:

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);
}
Al-Punk
  • 3,531
  • 6
  • 38
  • 56
  • Only curl? Heh, that was very easy to use file_get_contents. Anyway, appreciate your answer. – ABTOMAT Nov 21 '11 at 12:14
  • Hi @Al-Punk - what would be benefit of curl over file_get_contents in this example? (In general it's clear curl is more robust.) – itarato Oct 28 '14 at 11:14
  • @itarato file_get_contents is a simple method which does the job. cURL has a lot of options to refine your request. Think of file_get_contents as public-transportation which sends you some place, and think of curl of a Ferrari which is faster and gives you more pleasure in your trip. – Al-Punk Oct 30 '14 at 09:16
  • Thanks @Al-Punk I was wondering what could be difference. Maybe it has a different timeout, or request headers, etc. Thanks a lot ;) – itarato Oct 30 '14 at 15:48
  • 1
    @Al-Punk Do you have any references related to your claim Curl is faster? – e-sushi Mar 29 '18 at 00:55
  • Did a quick search: https://stackoverflow.com/a/37256025/277861 I have also done multiple tests many times ago, but have no benchmarks to present – Al-Punk Mar 31 '18 at 13:39