使用 file_get_contents 发送多个 Cookies
PHP 手册提供了一个示例,演示如何使用流上下文发送 cookie。但是,它没有解决发送多个 cookie 的场景。
多个 Cookie 选项
发送多个 cookie 有以下几种选项:
"Cookie: user=3345&pass=abcd\r\n"
此选项将 Cookie 合并为一个字符串,由与号 (&) 分隔。但是,它可能并不与所有服务器兼容。
"Cookie: user=3345\r\n" .
"Cookie: pass=abcd\r\n"
此选项将 cookie 作为带有单独 Cookie 标头的单独行发送。它提供了更好的兼容性,但可能看起来很混乱。
最佳解决方案
发送多个cookie的首选选项是:
Cookie: user=3345; pass=abcd
此语法使用分号 (;) 分隔 cookie 对。它受到广泛支持,并遵循 HTTP cookie 规范。
实现
使用 file_get_contents 发送多个 cookie:
$cookies = array('user' => '3345', 'pass' => 'abcd');
$cookieString = '';
foreach ($cookies as $name => $value) {
$cookieString .= "$name=$value;";
}
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Accept-language: en\r\n" .
"Cookie: $cookieString\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3