我正在編寫一個腳本來跟蹤標題,特別是重定向和Cookie的URL。 很多時候,當我打開一個url時,它會重定向到另一個url或有時多個url,並且還會存儲一些cookie。但是,當我跑的腳本URL跟蹤頁面標題和使用php-libcurl重定向
我的腳本didnt保存的cookies,而且只顯示一個重定向,並沒有任何儲存的Cookie。但是當我瀏覽Firefox中的url時,它保存了cookies,當我檢查它時,它顯示了多個獲取請求。 Live HTTP Headers還顯示有Set-Cookie標題。
<?php
$url="http://en.wikipedia.org/";
$userAgent="Mozilla/5.0 (Windows NT 5.1; rv:2.0)Gecko/20100101 Firefox/4.0";
$accept="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$encoding="gzip, deflate";
$header['lang']="en-us,en;q=0.5";
$header['charset']="ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header['conn']="keep-alive";
$header['keep-alive']=115;
$i=1;
$flag=1; //0 if there is no redirect i.e. no location header to follow. used here to to control the while loop below
while($flag!=0) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERAGENT,$userAgent);
curl_setopt($ch,CURLOPT_ENCODING,$encoding);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,0);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_NOBODY,1);
curl_setopt($ch,CURLOPT_AUTOREFERER,true);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookie.txt");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$pageHeader[$i]=curl_exec($ch);
curl_close($ch);
$flag=preg_match('/Location: (.*)\s/',$pageHeader[$i],$location[$i]);
if($flag==1) { //if there is a location header
if(preg_match('@^(http://|www.)@',$location[$i][1],$tempurl)==1) { //if it is an absolute url
$url=$location[$i][1];
} else {
if(preg_match('@^/(.*)@',$location[$i][1],$tempurl)==1) { //if the url corresponds to url relative to server's root
preg_match('@^((http://)|(www.))[^/][email protected]',$url,$domain);
$url=$domain.$tempurl[0];
} else { //if the url is relative to current directory
$url=preg_replace('@(/[^/]+)[email protected]',"/".$location[$i][1],$url);
}
}
$location[$i]=$url;
preg_match('/Set-Cookie: (.*)\s/',$pageHeader[$i],$cookie[$i]);
$i++;
}
foreach($location as $l)
$loc=$loc.$l."\n";
$header=implode("\n\n\n",$pageHeader);
file_put_contents(dirname(__FILE__) . "/location.txt",$loc);
file_put_contents(dirname(__FILE__) . "/header.txt",$header);
?>
這裏的文件location.txt
和header.txt
創建,但cookie.txt
不創建。 如果我將網址更改爲google.com,那麼它會在location.txt
文件中顯示重定向到google.co.in
,並將其保存在cookie.txt
文件中。但是當我在Firefox
中打開google.com
時,它節省了三個餅乾。什麼可能是錯誤的? 我認爲在設置cookie的頁面上有一些javascript,因此curl無法獲取。 也有任何建議,以改善上面的代碼,歡迎您
Daniel Stenberg:我已經修復了相關url的代碼,並且我認爲cookie沒有設置,因爲Cookie是由html頁面中的javascript設置的。我會在考試結束後的幾天內解決這個問題。謝謝您的幫助 – lovesh 2011-05-22 14:04:09