Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents and error codes

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.

like image 465
ABTOMAT Avatar asked Nov 20 '11 20:11

ABTOMAT


People also ask

Why does file_get_contents return false?

Your server may be preventing you from opening a file located at a URL using file_get_contents. if file_get_contents() returning false then it could not read the file. If the value is NULL then the function itself is disabled.

What is file_get_contents?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

Which is faster curl or file_get_contents?

Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

What does file_get_contents return?

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to length bytes. On failure, file_get_contents() will return false . file_get_contents() is the preferred way to read the contents of a file into a string.


2 Answers

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"
}
like image 147
Arseni Mourzenko Avatar answered Oct 21 '22 22:10

Arseni Mourzenko


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);
}
like image 21
Al-Punk Avatar answered Oct 21 '22 22:10

Al-Punk