2016-07-17 58 views
0

COOKIES我已經使用捲曲,使用PHP,請檢查下面的代碼如何讀取文本文件PHP

$cookie = "cookies.txt"; 
file_put_contents($cookie, ""); 
$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = curl_exec($ch); 

之後,我打開了cookies.txt文件中的cookie存儲。

現在我該如何閱讀該文件才能獲取所需的內容。

我試圖使用readfilefile_get_contents來讀取文件,但根本沒有用,這些只是返回空字符串。

請幫我一把。

在此先感謝

+0

爲什麼你需要讀取cookie文件? –

+0

你在哪裏設置file_get_contents? –

+0

從那個文件我需要得到2個特定的cookie,並設置不同的cookie名稱的值。 –

回答

1

CURL在會話結束時將cookie寫入文件。您的問題可能是您在CURL寫入Cookie之前訪問了Cookie文件。

可能的解決方法是之前結束捲曲會議試圖從cookie文件閱讀:

curl_easy_cleanup($ch); 
... 
$cookie_text = file_get_contents("cookies.txt"); 

See the docs.

作爲一種清潔的替代,只是抓住從餅乾直接回復,無需通過cookies.txt文件。下面的代碼就會把餅乾在數組中爲您提供:從這個accepted answer採取

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches); 
$cookies = array(); 
foreach($matches[1] as $item) { 
    parse_str($item, $cookie); 
    $cookies = array_merge($cookies, $cookie); 
} 

代碼: