php获得远程文件大小的函数
php获得远程文件大小的函数
文件的大小函数为:filesize()
文件是否存在的函数为:file_exits();
但是这两个函数只针对本地
那么:远程文件是否存在,远程文件大小 如何得知呢?
搜索了一下,有人居然说,把远程文件下载过来再判断这个远程文件的大小,这是什么歪理。
庆幸大部分人还是清醒的,一般应该使用判断header反馈的信息进行判断。
php中如何获得header信息呢? php的函数真多,这个也不例外
1.最简单的获取远程文件大小办法
$a_array = get_headers(url,true);
url就是网址了,至于第二个参数
就可以得到类似下面的这个数组
Array ( [0] => HTTP/1.1 200 OK [Date] => Sat, 29 May 2004 12:28:14 GMT [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT [ETag] => "3f80f-1b6-3e1cb03b" [Accept-Ranges] => bytes [Content-Length] => 438 [Connection] => close [Content-Type] => text/html )
所以,你可以很舒服的拿到远程文件的大小
$file_sizeofurl =a_array['Content-Length'];
2.用curl获取远程文件大小
如果服务器禁止get_headers 怎么办?
换一种办法,用curl
我总觉得curl就像一个虚拟的用户,什么都能模仿
下面直接给出一个老外的函数
请注意
echo'head-->'.$head.'<----end';
这句是我加的,为了知道header里面到底包含了什么东西
function remote_filesize($uri,$user='',$pw='')
{
// start output
buffering
ob_start();
// initialize curl with given uri
$ch =
curl_init($uri);
// make sure we get the header
curl_setopt($ch, CURLOPT_HEADER, 1);
// make it a http HEAD request
curl_setopt($ch, CURLOPT_NOBODY, 1);
// if auth is needed, do it here
if (!emptyempty($user) && !emptyempty($pw))
{
$headers = array('Authorization: Basic ' .
base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$okay = curl_exec($ch);
curl_close($ch);
// get the
output buffer
$head = ob_get_contents();
// clean the output buffer and
return to previous
// buffer settings
ob_end_clean();
echo'head-->'.$head.'<----end ';
// gets you the numeric value from the Content-Length
// field in the http header
$regex = '/Content-Length:s([0-9].+?)s/';
$count = preg_match($regex, $head, $matches);
// if there was a Content-Length field, its value
// will now be in $matches[1]
if (isset($matches[1]))
{
$size = $matches[1];
}
else
{
$size = 'unknown';
}
//$last=round($size/(1024*1024),3);
//return $last.' MB';
return$size;
}3.fsock获取远程文件大小的办法
先给函数
function getFileSize($url){
$url = parse_url($url);
if($fp = @fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)){
fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])."HTTP/1.1rn");
fputs($fp,"Host:$url[host]rnrn");
while(!feof($fp)){
$tmp = fgets($fp);
if(trim($tmp) == ''){
break;
}elseif(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
return trim($arr[1]);
}
}
returnnull;
}else{
returnnull;
}
}哪个获取远程文件大小最快?
针对同一个url进行测试,curl > fsock > getheader
针对不同url测试,结果还是 curl > fsock > getheader
当然也许这个测试是不准确的,但getheader函数是明显要慢一些的
考虑到curl模块没有fsock那么普及,所以我自己还是用后面一个
速度上的差别大约是 curl比fsock快0.2秒,fsock比getheader快0.2秒。
一、推荐使用迅雷或快车等多线程下载软件下载本站资源。
二、未登录会员无法下载,登录后可获得更多便利功能,若未注册,请先注册。
三、如果服务器暂不能下载请稍后重试!总是不能下载,请点我报错 ,谢谢合作!
四、本站大部分资源是网上搜集或私下交流学习之用,任何涉及商业盈利目的均不得使用,否则产生的一切后果将由您自己承担!本站将不对任何资源负法律责任.如果您发现本站有部分资源侵害了您的权益,请速与我们联系,我们将尽快处理.
五、如有其他问题,请加网站设计交流群(点击这里查看交流群 )进行交流。
六、如需转载本站资源,请注明转载来自并附带链接
七、本站部分资源为加密压缩文件,统一解压密码为:www.aizhanzhe.com
