如何在CURL重定向上传递cookie?

时间:2009-09-22 07:50:35

标签: php cookies redirect curl

想象一下以下场景:我打开一个CURL连接并通过POST传递一些XML-Logindata。服务器使用302重定向进行应答,其中会话cookie已设置并将我重定向到以下“欢迎”页面。如果我启用FOLLOWLOCATION,重定向页面上设置的cookie将丢失,欢迎页面将失败并显示“会话已过期”消息。如果我禁用FOLLOWLOCATION,我不会被重定向(显然)并获得一个HTML页面,其中“页面已移动到另一个位置”,其中的链接将引导我访问欢迎页面。这可以在设置cookie时起作用,但我需要按照重定向直接进入欢迎页面。

那么,如何保持cookie以便正确设置?

到目前为止,这是我的代码:

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

感谢您的帮助! ;

4 个答案:

答案 0 :(得分:28)

这是一个老问题,但我遇到了同样的问题,所以谷歌把我带到了这里。 最后,我设法解决了这个问题。 通过使用curl_setopt传递空字符串“”来设置CURLOPT_COOKIEFILE将解决问题:

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

请参阅http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

CURLOPT_COOKIEFILE部分

答案 1 :(得分:6)

指示php在curl会话上使用cookies你应该设置两个选项:

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

所以每个cookie都将附加在CURLOPT_COOKIEJAR上,并且这些cookie将通过设置CURLOPT_COOKIEFILE

在每个位置进行

答案 2 :(得分:3)

为了回答自己,我就这样做了:

抓住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;

}

答案 3 :(得分:2)

您可能也想查看此库:http://github.com/shuber/curl