Get Response Header from file_get_contents in PHP

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

A URL can be used as a filename with this function if the fopen wrappers have been enabled.

But, reading URL becomes difficult to identify that URL is not available. And if URL is not available, it’s also difficult to process that URL. So, it is necessary that there is a response for every request fired by file_get_contents() for any URL.

PHP has a predefined variable named $http_response_header, which provides a response header for any HTTP request sent by PHP code.

For Example,

file_get_contents("http://example.com");
var_dump($http_response_header);

The above example will output something similar to:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won’t appear in $http_response_header.

The cURL extension doesn’t have this limit.