There's a magic variable for this, called $http_response_header
; it's an array comprising all headers that were received. To extract the cookies you have to filter out the headers that start with Set-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;
}
}
print_r($cookies);
An equivalent but less magical approach would be to use 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…