如何使用MegaBytes、KiloBytes等将PHP的filesize()
函数的输出转换成一种很好的格式?
像这样:
(GB
发布于 2011-03-31 22:28:26
下面是一个示例:
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
?>
发布于 2012-08-08 16:32:50
更好的是我用我找到的a plugin创建的这个版本:
function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
来自filesize() doc的注释
由于PHP的整数类型是有符号的,并且许多平台使用32位整数,因此对于大于2 2GB
的文件,某些文件系统函数可能会返回意外的结果
发布于 2011-03-31 23:10:40
一种更干净的方法:
function Size($path)
{
$bytes = sprintf('%u', filesize($path));
if ($bytes > 0)
{
$unit = intval(log($bytes, 1024));
$units = array('B', 'KB', 'MB', 'GB');
if (array_key_exists($unit, $units) === true)
{
return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
}
}
return $bytes;
}
https://stackoverflow.com/questions/5501427
复制相似问题