如何在CURL重定向上传递cookie? [英] How do I pass cookies on a CURL redirect?

查看:510
本文介绍了如何在CURL重定向上传递cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设想以下情形:我打开一个CURL连接,并通过POST传递一些XML-Logindata。服务器回答302重定向,其中设置了会话cookie,并将我重定向到以下欢迎页面。如果启用FOLLOWLOCATION,则在重定向页面上设置的cookie会丢失,并且欢迎页面会失败,并显示会话已过期消息。如果禁用FOLLOWLOCATION,则不会重定向(很明显),并且不会获得带有页面已移至另一个位置的HTML页面,该页面带有一个链接,该链接会将我带到欢迎页面。这样就可以设置cookie,但是我需要遵循重定向并直接进入欢迎页面。

imagine the following scenario: I open a CURL connection and pass some XML-Logindata via POST. The server answers with an 302 redirect, where the session cookies are set and redirects me to a following "welcome"-page. If I enable FOLLOWLOCATION the cookies set on the redirection-page get lost and the welcome-page fails with a "session expired"-message. If I disable FOLLOWLOCATION, I'm not redirected (obviously) and get a HTML-page with "the page has moved to another location" with a link that leads me to the welcome-page. This works as the cookies are set, but I need to follow the redirect and go straight to the welcome-page.

因此,我如何维护cookie,以便它们设置正确吗?

So, how do I maintain the cookies so that they are set correctly?

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

This is my code so far:

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

感谢您的帮助!
;

Thanks for any help! ;

推荐答案

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

This is an old question, but I had the same problem, so google took me here. Finally, I managed to solve it. By passing an empty string "" to set CURLOPT_COOKIEFILE using curl_setopt will solve the problem:

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

请参见CURLOPT_COOKIEFILE 部分 http://curl.haxx.se/libcurl/c/curl_easy_setopt.html rel = noreferrer> http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

See section CURLOPT_COOKIEFILE of http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

这篇关于如何在CURL重定向上传递cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆