PHP: get_headers set temporary stream_context

隐身守侯 提交于 2019-11-29 10:30:16

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.

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:

$options = array(
               'http' => array(
                     'method' => 'HEAD',
                     'follow_location' => 0
                )
           );

$context = stream_context_create($options);

@file_get_contents($url, NULL, $context);

var_dump($http_response_header);

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.)

$stream_context_defaults = stream_context_get_options(stream_context_get_default());
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
for ($i = 1; $i <= 10; $i++) {
    $headers = get_headers('http://www.example.org');
}
stream_context_set_default($stream_context_defaults); // reset to defaults
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!