کد PHP:
<?php
function FormatSize($url, $remote = false, $precision = 2) {
$bytes = 0;
if(!$remote) {
if(file_exists($url)) {
$bytes = filesize($url);
}
}
else {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Not necessary unless the file redirects
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
return -1;
}
if (preg_match('#Content-Length: (\d+)#i', $data, $matches)) {
$bytes = trim($matches[1]);
}
}
settype($bytes, 'double');
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$len = count($units);
for ($i = 0; $bytes >= 1024 && $i < $len; $i++) {
$bytes /= 1024;
}
return round($bytes, $precision) . $units[$i];
}
/* Usage Samples:
echo '<p>' . FormatSize('images/logo.png') . '</p>' . PHP_EOL;
echo '<p>' . FormatSize('http://www.google.com/images/srpr/logo4w.png', true) . '</p>' . PHP_EOL;
*/
?>