PHP:get_headers 设置临时 stream_context

2022-01-11 00:00:00 http-headers stream header head php

我猜 PHP 的 get_headers 不允许上下文,所以我必须更改默认流上下文以仅获取请求的 HEAD.这会导致页面上的其他请求出现一些问题.我似乎无法弄清楚如何重置默认流上下文.我正在尝试类似:

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?

我知道有人建议使用 Curl,但我宁愿不使用这个.谢谢!

I know it has been suggested to use Curl, but I would rather not for this one. Thanks!

推荐答案

我最终使用了 stream_get_meta_data() 函数获取 HTTP 标头.

I ended up using the stream_get_meta_data() function to get the HTTP headers.

我是这样实现的:

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;
}

这样称呼,

$context = stream_context_create(array('http' => array('method' => 'HEAD')));
$headers = get_headers_with_stream_context($url, $context, 1);

它在保持标准 stream_context 不变的情况下为您提供您所追求的.

it gives you what you're after while leaving the standard stream_context unmodified.

请注意,如果传递的不是 http url,此函数将失败.

Please note that this function will fail if passed anything other than an http url.

似乎有一个 功能请求 用于 get_headers() 的附加参数,但错误在我写这篇文章时跟踪器已关闭,所以我无法在那里检查其他解决方案.

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.

相关文章