2013-10-10 92 views
6

我試圖在curl cookiejar中保存一個cookie。我已簡化了我的代碼,但它不起作用。爲什麼php curl不能將cookie保存在我的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服務器: 阿帕奇/ 2.4。 4(Win64)PHP/5.4.12 X-Powered-by:PHP/5.4.12 Set-Cookie: TestCookie = something + from + somewhere Content-Length:0 Content-Type: text/html

所以testcookie在標題中,但我的cookie文件保持爲空。我做錯了什麼?我可以嘗試使這個例子有效嗎?謝謝!

回答

14

設置CURLOPT_COOKIEJAR時,需要使用絕對路徑。您可以通過使用很容易地做到這一點:

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

參考:cannot use cookies in cURL PHP

+0

謝謝!我一直在爲此奮鬥了幾個小時,甚至嘗試過絕對路徑,但它不起作用。 realpath做了訣竅。再次感謝你。 –

+2

'realpath'會返回絕對路徑,所以當你遇到這個問題時你做錯了什麼。 –

+3

CURLOPT_COOKIEJAR絕對路徑僅適用於Windows平臺。在Linux/Unix路徑中可以是相對的。我檢查了它。 –