I guess PHP's get_headers does not allow for a context, so I have to change the default stream context to only get the HEAD of a request. This causes some issues with other requests on the page. I can't seem to figure out how to reset the default stream context. I'm trying something like:
$default = stream_context_get_default(); //Get default stream context so we can reset it
stream_context_set_default( //Only fetch the HEAD
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers($url, 1); //Url can be whatever you want it to be
//var_dump($headers);
var_dump($default);
stream_context_set_default($default); //This doesn't work as it expects an array and not a resource pointer
Does anyone know a fix for this?
I know it has been suggested to use Curl, but I would rather not for this one. Thanks!
I had a similar issue but I just used the
file_get_contents
function with the custom stream context instead.Here's how I implemented it:
Using this context only the headers will be fetched by
file_get_contents
and will populate the$http_response_header
PHP variable.Instead of the accepted answer, I did the following, which will work in PHP 5.3 and above, though I haven't fully tested it. (There's also a
stream_context_get_params($context)
but I think this is enough.)I ended up using the stream_get_meta_data() function to get the HTTP headers.
This is how I implemented it:
Called like this,
it gives you what you're after while leaving the standard stream_context unmodified.
Please note that this function will fail if passed anything other than an http url.
There seems to be a feature request for an additional argument for get_headers(), but the bug tracker is down as I'm writing this, so I can't check for other solutions there.