php file_get_contents()请求页面时获取cookie值

时间:2016-09-01
需求是这样的,使用file_get_contents请求页面并获取cookie值,然后使用这个cookie值第二次获取页面内容,该如何实现呢?具体代码请看下面实例。

使用file_get_contents获取页面内容后,我们可以使用$http_response_header获取响应头信息,响应头信息里面一般包括cookie变量的值,具体实现代码如下:

file_get_contents('http://example.org');

$cookies = array();
foreach ($http_response_header as $hdr) {
    if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
        parse_str($matches[1], $tmp);
        $cookies += $tmp;
    }
}
/*  http://www.manongjc.com/article/1429.html */
print_r($cookies);

例外一种方法可以使用stream_get_meta_data()实现:

if (false !== ($f = fopen('http://www.example.org', 'r'))) {
        $meta = stream_get_meta_data($f);
        $headers = $meta['wrapper_data'];

        $contents = stream_get_contents($f);
        fclose($f);
}
// $headers now contains the same array as $http_response_header