12

我正在尝试在 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;
?> 

设置cookie.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 保持为空。我做错了什么?我该怎么做才能使这个例子起作用?谢谢你!

4

4 回答 4

20

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

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

参考:不能在 cURL PHP 中使用 cookie

于 2013-10-10T12:23:08.730 回答
0

作为参考CURLOPT_COOKIEJAR:_

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

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

使用curl_close($ch);after curl_exec,将 cookie 保存在 jar 文件中。

于 2018-09-15T20:28:45.170 回答
0

是的 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
于 2018-11-23T20:47:53.100 回答
0

我尝试了所有事情,对我有用的是放置cookie文件的绝对路径

 curl_setopt($ch, CURLOPT_COOKIEJAR, '/var/www/myapp/cookies.txt' ); 
 curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/myapp/cookies.txt' );
于 2021-10-19T11:12:55.197 回答