I ended up using the stream_get_meta_data() function to get the HTTP headers.
This is how I implemented it:
function get_headers_with_stream_context($url, $context, $assoc = 0) {
$fp = fopen($url, 'r', null, $context);
$metaData = stream_get_meta_data($fp);
fclose($fp);
$headerLines = $metaData['wrapper_data'];
if(!$assoc) return $headerLines;
$headers = array();
foreach($headerLines as $line) {
if(strpos($line, 'HTTP') === 0) {
$headers[0] = $line;
continue;
}
list($key, $value) = explode(': ', $line);
$headers[$key] = $value;
}
return $headers;
}
Called like this,
$context = stream_context_create(array('http' => array('method' => 'HEAD')));
$headers = get_headers_with_stream_context($url, $context, 1);
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…