PHP:get_headers设置临时stream_context [英] PHP: get_headers set temporary stream_context

查看:444
本文介绍了PHP:get_headers设置临时stream_context的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这样调用,

Called like this,

$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()提供了一个额外的参数,但是当我写这个的时候bug跟踪器已经关闭了,所以我可以在那里检查其他解决方案。

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.

这篇关于PHP:get_headers设置临时stream_context的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆