我正在编写一个脚本来跟踪标题,特别是重定向和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