Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

header - PHP: get_headers set temporary stream_context

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...