想象一下下面的场景:我打开一个CURL连接,并通过POST传递一些XML-Logindata。服务器以302重定向应答,其中设置了会话cookie,并将我重定向到下面的“欢迎”-page。如果我启用FOLLOWLOCATION,重定向页面上设置的-message将丢失,欢迎页面将失败,并显示“会话已过期”cookie。如果我禁用了FOLLOWLOCATION,我不会被重定向(很明显),并且会得到一个带有“该页面已移动到另一个位置”的HTML页面以及一个指向欢迎页面的链接。这在设置cookie时起作用,但我需要遵循重定向并直接转到欢迎页面。
那么,如何维护cookies以便正确设置它们呢?
这是我到目前为止的代码:
$ch = curl_init('https://www.example.com/login');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '<some xml data>');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml; charset=UTF-8"));
curl_exec($ch);
curl_close($ch)谢谢你的帮助!
发布于 2012-09-09 20:58:36
这是一个老问题,但我也有同样的问题,所以谷歌把我带到了这里。最后,我设法解决了这个问题。通过传递一个空字符串"“来使用curl_setopt设置CURLOPT_COOKIEFILE,可以解决这个问题:
curl_setopt($ch, CURLOPT_COOKIEFILE, "");请参阅http://curl.haxx.se/libcurl/c/curl_easy_setopt.html的CURLOPT_COOKIEFILE一节
发布于 2010-08-26 05:13:48
要指示curl会话上的php使用cookie,您应该设置两个选项:
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');// set where cookies will be stored
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');// from where it will get cookies因此,通过设置CURLOPT_COOKIEFILE,每个cookie都将被附加到CURLOPT_COOKIEJAR上,并且这些cookie将被带到每个位置
发布于 2009-09-22 09:45:14
为了回答我自己,我是这样做的:
抓取header-http-status代码。如果是重定向,则提取新位置并手动重定向。否则,移除头部并输出内容:
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if($info['http_code'] == 301 || $info['http_code'] == 302) { // redirect manually, cookies must be set, which curl does not itself
// extract new location
preg_match_all('|Location: (.*)\n|U', $response, $results);
$location = implode(';', $results[1]);
// redirect manually
header("Location: $location");
exit;
} else { // no redirect, remove header and output directly
$response = substr_replace($response, '', 0, strpos($response, '<', 0));
echo $response;
}https://stackoverflow.com/questions/1458683
复制相似问题