php获取远程图片体积大小
实测可用,基本准确,进行了一小部分修改,返回的是字节。
/*
//用法 echo remote_filesize($url,$user='',$pw='');
获取远程图片的尺寸大小
*/
function remote_filesize($uri, $user='', $pw=''){
// start output buffering
ob_start();
// initialize curl with given uri
// make sure we get the header
$ch = curl_init($uri);
// make it a http HEAD request
curl_setopt($ch, CURLOPT_HEADER, 1);
// if auth is needed, do it here
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);
// get the output buffer
curl_close($ch);
// clean the output buffer and return to previous // buffer settings
$head = ob_get_contents();
ob_end_clean();
// gets you the numeric value from the Content-Length // field in the http header
$regex = '/Content-Length:\s([0-9].+?)\s/';
// if there was a Content-Length field, its value
$count = preg_match($regex, $head, $matches);
// will now be in $matches[1]
if (isset($matches[1])) {
$size = $matches[1];
} else {
$size = 0;
}
// $last=round($size/(1024*1024),3);
// return $last.' MB';
return $size;
}
函数的思路是,先CURL获取图片到缓冲区,然后正则获取图片的Content-Length信息就OK了。