如何将PHP的filesize()
函数的输出转换为带有MB、KB等格式的好格式?
例如:
- 如果大小小于1MB,则以KB为单位显示大小。
- 如果大小在1MB到1GB之间,则以MB为单位显示。
- 如果大小大于1GB,则以GB为单位显示。
function getNiceFileSize($file, $digits = 2){
if (is_file($file)) {
$filePath = $file;
if (!realpath($filePath)) {
$filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
}
$fileSize = filesize($filePath);
$sizes = array("TB", "GB", "MB", "KB", "B");
$total = count($sizes);
while ($total-- && $fileSize > 1024) {
$fileSize /= 1024;
}
return round($fileSize, $digits) . " " . $sizes[$total];
}
return false;
}
size_format()
。 - Earlee