php获取远程文件大小


使用条件:需要服务器支持Curl组件

<?php
 
function remote_filesize($url,$user='',$pw='')
{
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if (!empty($user)&&!empty($pw)) {
$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$okay = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:s([0-9].+?)s/';
$count = preg_match($regex, $head, $matches);
if (isset($matches[1])) {
$size = $matches[1];
} else {
$size = 'unknown';
}
return $size;
}
//计算远程文件大小
$url = "http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011.exe";
$filesize = remote_filesize($url,$user='',$pw='')/1024/1024;
//显示远程文件大小
echo substr($filesize,0,5)."MB";
 
?>

发表回复