我正在通过站点 B 上的 CURL 从站点 A 登录,我从连接中获取 cookie 并写入名为 cookie.txt 的文件。
但是当我传递 cookie 数据以执行最终标头重定向("位置:http://examplesiteb.com"(时,它会返回断开连接。
我用于连接的代码与另一篇文章中的代码相同,但我根据@ramrider用户的建议进行了修改,我建议在标头中传递cookie,但我不确定应该如何做到这一点。
将 cookie 和会话从 CURL 传输到标头位置
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 10);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
// Download the given URL, and return output
$output = curl_exec($ch);
// Cookie Match
preg_match_all('/^Set-Cookie:s*([^rn]*)/mi', $output, $ms);
$cookies = array();
foreach ($ms[1] as $m) {
list($name, $value) = explode('=', $m, 2);
$cookies[$name] = $value;
header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value));
}
//print_r($cookies);
$redirect = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
header("Location: $redirect");
//Close Match
curl_close($ch);
重定向发生,但不会保持登录状态。
在示例 cookie 文件下方
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_example.com FALSE / FALSE 0 ASP.NET_SessionId 10gtonkebkteuazx24sajlh2
#HttpOnly_example.com FALSE / TRUE 1515800212 DTE 898EC9C0EF0BA3985E402046547931EAA55808E14A2DE469F11F6F6C0CF9A28871C8704BE794885CDF7D3EE1E8B06698166F86C184C5B53FE61FA53CA13682C562E17BCB7B2FA16D7A7180E6EA973735
用户@martijn-pieters和@waqas-bukhary,如果他们能提供帮助,我谢谢你,因为你在另一篇文章中删除了我的答案,我正在为其他人完成我找不到解决方案的其他信息。
谢谢
Cookie 与发送它们的域相关联。 您不能为其他域设置 Cookie。
如果example.com
"站点 B"(您使用 cURL 登录"站点 A"(not-example.com
,则Set-Cookie
设置的 cookie 适用于example.com
,不适用于not-example.com
。
没有为您自己的域以外的域设置 Cookie 的机制。
请参阅 RFC 6265 第 5.3 节(存储模型(第 6 部分:
如果域属性为非空:
如果规范化的请求主机与域属性不匹配:
- 完全忽略 Cookie 并中止这些步骤。
这实际上表明,如果站点 A 尝试为站点 B 设置 cookie,浏览器必须忽略 cookie。