【问题标题】:How do I pass cookies on a CURL redirect?如何在 CURL 重定向上传递 cookie?
【发布时间】:2010-11-30 07:54:51
【问题描述】:

想象以下场景:我打开一个 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)

感谢您的帮助! ;

【问题讨论】:

    标签: php cookies redirect curl


    【解决方案1】:

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

    curl_setopt($ch, CURLOPT_COOKIEFILE, "");
    

    http://curl.haxx.se/libcurl/c/curl_easy_setopt.htmlCURLOPT_COOKIEFILE部分

    【讨论】:

      【解决方案2】:

      要在 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
      

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

      【讨论】:

        【解决方案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;
        
        }
        

        【讨论】:

        • 所以要明确一点,您不再设置 CURLOPT_FOLLOWLOCATION 了吗?
        【解决方案4】:

        你可能也想看看这个库:http://github.com/shuber/curl

        【讨论】:

          猜你喜欢
          • 2016-05-18
          • 1970-01-01
          • 2017-06-30
          • 1970-01-01
          • 2014-02-25
          • 1970-01-01
          • 2012-09-29
          • 2016-12-22
          • 2020-09-29
          相关资源
          最近更新 更多