gpt4 book ai didi

php - file_get_contents 接收 cookie

转载 作者:IT王子 更新时间:2023-10-28 23:50:45 32 4
gpt4 key购买 nike

在执行 file_get_contents 请求时,是否可以接收远程服务器设置的 cookie?

我需要 php 发出一个 http 请求,存储 cookie,然后使用存储的 cookie 发出第二个 http 请求。

最佳答案

有一个神奇的变量,叫做 $http_response_header;它是一个包含所有接收到的 header 的数组。要提取 cookie,您必须过滤掉以 Set-Cookie: 开头的 header 。

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

一种等效但不那么神奇的方法是使用 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

关于php - file_get_contents 接收 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797510/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com