为什么php curl不会在我的cookiefile中保存cookie?

kas*_*ans 9 php cookies curl cookiejar

我正在尝试在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;
?> 
Run Code Online (Sandbox Code Playgroud)

setcookie.php

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

?>
Run Code Online (Sandbox Code Playgroud)

收到标题

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 =某事+来自+某处Content-Length:0 Content-Type:text/html

所以testcookie在标题中,但我的cookiefile保持空白.我做错了什么?我可以尝试使这个例子有效吗?谢谢!

Jer*_*ris 18

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

curl_setopt ($ch, CURLOPT_COOKIEJAR, realpath($cookie_file) );
Run Code Online (Sandbox Code Playgroud)

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

  • CURLOPT_COOKIEJAR绝对路径仅适用于Windows平台.在Linux/Unix路径中可以是相对的.我检查了一下. (3认同)
  • `realpath`返回绝对路径,所以当你正在努力解决这个问题时,你做错了什么. (2认同)