Getting HTTP response headers when using file_get_contents()
Published September 2nd, 2005This one’s more of a reminder for me than anything else. When retrieving data from a remote URL with file_get_contents() in PHP, it’s possible that the request will return an error code (eg. 404 File Not Found). As it happens, when you make this sort of request PHP creates an array called $http_response_header which — surprise! — contains the HTTP response headers for the request. Here’s some example output:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Fri, 02 Sep 2005 08:25:38 GMT
[2] => Server: Apache
[3] => X-Powered-By: PHP/5.0.4
[4] => Content-Length: 1881
[5] => Connection: close
[6] => Content-Type: text/html
)
Note that it’s a numeric rather than associative array — from my limited knowledge of HTTP headers, I’m assuming the element 0 (zero) will always be the status code so it’s a pretty simple matter to check for anything other than 200.
Jonathan on December 1, 2009
I have been searching for some time now, thank you for posting it.