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.
Roy on March 13, 2010
I want to suggest this free http testing tool using this tool you can send different HTTP request with different options/protocols/header/cache and view the text Response from any URL.
Actually you can see if the you getting the right headers from the server
http://soft-net.net/SendHTTPTool.aspx
Tack on September 25, 2010
This is a very useful tip, thanks for that. What isn’t useful is how PHP implicitly and magically inserts crap into my local scope which should instead be part of the return value, or at the very least passed as an array reference at invocation time. My god how PHP makes me want to gouge out my eyes.
Stickman on September 26, 2010
When working with PHP, one has to bear in mind that it’s still carrying the baggage of its procedural past around with it — and this will almost certainly never change. If you want a fully OOP langauge there are plenty of alternatives out there: Ruby being probably the closest equivalent.
Personally, over time I’ve become rather desensitised to PHP’s quirks and while I’m happy working in a pure OOP environment too, when working in PHP I don’t find it so hard to separate my own OOP-styled code from the clumsy procedural bits of PHP that are required. No programming language is without its flaws: PHP’s might be more obvious (and possibly, numerous) than some others but with discipline you can still write good code with it.
dj on May 9, 2011
thanks man,
was looking for this!!!
sometimes you dont have the luxory of Curl installed,
then you need a workaround
spaecially if it is a redirect header, you want to know where you are being redirected (thanks!)
now, we can see it in this variable, thanks again!