【发布时间】:2018-06-22 19:19:56
【问题描述】:
我通过站点 B 上的 CURL 从站点 A 登录,我从连接中获取 cookie 并写入名为 cookie.txt 的文件。
但是当我传递 cookie 数据进行最终的标头重定向时('Location: http://examplesiteb.com'),它返回断开连接。
我用于连接的代码与其他帖子中的代码相同,但我根据@ramrider 用户的建议进行了修改,我建议在标题中传递 cookie,但我不确定应该如何完成.
Transfer cookies & session from CURL to header location
$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*([^\r\n]*)/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 可以提供帮助,我将感谢您,因为您删除了我在另一篇帖子中的答案,并且我正在为其他人完成我无法找到解决方案的其他信息。
谢谢
【问题讨论】:
标签: php curl cookies session-cookies