Reputation: 62366
I'm using a file_get_contents
to interact with an API for simple GET
requests... however sometimes it throws headers signifying there's been an error. How can I get these headers and determine if there's a problem?
Upvotes: 1
Views: 4239
Reputation: 22000
Php will set $http_response_header after file_get_contents
which contains the response headers as an array of header lines/strings. Its not necessary to use curl if all you want is the headers responses (and probably shouldn't, some LAMP stacks still don't have cURL).
Doc on $http_response_header: http://php.net/manual/en/reserved.variables.httpresponseheader.php
Example:
file_get_contents('http://stacksocks.com');
foreach ($http_response_header as $header)
{
echo $header . "<br>\n";
}
Tips taken from post in comments:
1) The value changes with each request made.
2) When used in methods/functions, the current value must be passed to the method/function. Using $http_response_header directly in the method/function without being assigned a value by a function/method parameter will result in the error message: Notice: Undefined variable: http_response_header
3) The array length and value locations in the array may change depending on the server being queried and the response received. I'm not sure if there are any 'absolute' value positions in the array.
4) $http_response_header ONLY gets populated using file_get_contents() when using a URL and NOT a local file. This is stated in the description when it mentions the HTTP_wrapper.
Upvotes: 5
Reputation: 2669
Use curl instead of file_get_contents.
See: http://www.php.net/manual/en/curl.examples-basic.php
I imagine if your communicating with a REST Api then your actaully wanting the Http Status code returned. In which case you could do something like this:
<?php
$ch = curl_init("http://www.example.com/api/users/1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
echo 'Ops it not implemented';
}
fclose($fp);
?>
Upvotes: 4
Reputation: 7993
file_get_contents('http://example.com');
var_dump($http_response_header);
Upvotes: 0