【问题标题】:Why php curl does not save cookie in my cookiefile?为什么 php curl 不在我的 cookiefile 中保存 cookie?
【发布时间】:2013-10-18 04:51:36
【问题描述】:

我正在尝试在 curl cookiejar 中保存一个 cookie。我已经简化了我的代码,但它不起作用。

<?php

$cookie_file = './cookies.txt';

if (! file_exists($cookie_file) || ! is_writable($cookie_file)){
    echo 'Cookie file missing or not writable.';
    exit;
}//cookie_file is writable, so this is not the issue

$ch = curl_init (html_entity_decode("http://localhost/kiala_test/setcookie.php"));
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec ($ch);
echo $output;
?> 

setcookie.php

<?php 
$value = 'something from somewhere';
setcookie("TestCookie", $value);

?>

收到标题

HTTP/1.1 200 OK 日期:2013 年 10 月 10 日星期四 12:10:37 GMT 服务器: Apache/2.4.4 (Win64) PHP/5.4.12 X-Powered-By: PHP/5.4.12 Set-Cookie: TestCookie=something+from+somewhere 内容长度:0 内容类型: 文本/html

所以 testcookie 在标题中,但我的 cookiefile 保持为空。我做错了什么?我该怎么做才能使这个例子起作用?谢谢!

【问题讨论】:

    标签: php cookies curl cookiejar


    【解决方案1】:

    设置CURLOPT_COOKIEJAR时,需要使用绝对路径。您可以使用以下方法轻松完成此操作:

    curl_setopt ($ch, CURLOPT_COOKIEJAR, realpath($cookie_file) );
    

    参考:cannot use cookies in cURL PHP

    【讨论】:

    • 谢谢!我已经为此苦苦挣扎了几个小时,甚至尝试了绝对路径,但它不起作用。 realpath 成功了。再次感谢您。
    • realpath 返回绝对路径,所以当您为此苦苦挣扎时,您做错了。
    • CURLOPT_COOKIEJAR 绝对路径仅适用于 Windows 平台。在 Linux/Unix 中,路径可以是相对的。我查过了。
    【解决方案2】:

    作为reference 关于CURLOPT_COOKIEJAR

    句柄关闭时保存所有内部 cookie 的文件的名称,例如在调用 curl_close 之后。

    所以,在你的代码中没有使用curl_close

    curl_exec 之后使用curl_close($ch);,将cookies 保存在jar 文件中。

    【讨论】:

      【解决方案3】:

      是的 realpath 有效,但请记住(感谢 php.net)在 curl_exec 的第二次调用之前,CURLOPT_COOKIEFILE 应该与 CURLOPT_COOKIEJAR 的先前设置相同 - 因为它用于从“jared”文件中读取:)

      //my working snippet for one php file:
      //....
      curl_setopt($ch, CURLOPT_COOKIEJAR, realpath('test2-cookie.txt'));
      $content = curl_exec($ch);
      curl_close($ch); 
      $ch = curl_init();  
      curl_setopt($ch, CURLOPT_COOKIEJAR, realpath('test2-cookie.txt'));
      curl_setopt ($ch, CURLOPT_COOKIEFILE, realpath('test2-cookie.txt'));
      $content = curl_exec($ch);//second call
      

      【讨论】:

        【解决方案4】:

        我尝试了所有方法,对我有用的是为 cookie 文件设置绝对路径

         curl_setopt($ch, CURLOPT_COOKIEJAR, '/var/www/myapp/cookies.txt' ); 
         curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/myapp/cookies.txt' );
        

        【讨论】:

          猜你喜欢
          • 2015-12-03
          • 2011-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-12
          • 2019-01-11
          • 1970-01-01
          相关资源
          最近更新 更多