PHP 文件大小 MB/KB 转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5501427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP filesize MB/KB conversion
提问by Alex
How can I convert the output of PHP's filesize()
function to a nice format with MegaBytes, KiloBytes etc?
如何filesize()
使用 MegaBytes、KiloBytes 等将 PHP函数的输出转换为一个不错的格式?
like:
喜欢:
- if the size is less than 1 MB, show the size in KB
- if it's between 1 MB - 1 GB show it in MB
- if it's larger - in GB
- 如果大小小于 1 MB,则以 KB 为单位显示大小
- 如果它介于 1 MB - 1 GB 之间,则以 MB 为单位显示
- 如果它更大 - 以 GB 为单位
回答by Adnan
Here is a sample:
这是一个示例:
<?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;
}
?>
回答by PiTheNumber
Even nicer is this version I created from a pluginI found:
更好的是我从我发现的插件创建的这个版本:
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];
}
Note from filesize() doc
来自文件大小()文档的注释
Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB
由于 PHP 的整数类型是有符号的,并且许多平台使用 32 位整数,因此对于大于 2GB 的文件,某些文件系统函数可能会返回意外结果
回答by Alix Axel
A cleaner approach:
更清洁的方法:
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;
}
回答by Teffi
I think this is a better approach. Simple and straight forward.
我认为这是一个更好的方法。简单直接。
public function sizeFilter( $bytes )
{
$label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
return( round( $bytes, 2 ) . " " . $label[$i] );
}
回答by Jens A. Koch
This is based on @adnan's great answer.
这是基于@adnan 的精彩回答。
Changes:
变化:
- added internal filesize() call
- return early style
- saving one concatentation on 1 byte
- 添加了内部文件大小()调用
- 回归早期风格
- 在 1 个字节上保存一个串联
And you can still pull the filesize() call out of the function, in order to get a pure bytes formatting function. But this works on a file.
您仍然可以将 filesize() 调用从函数中拉出,以获得纯字节格式化函数。但这适用于文件。
/**
* Formats filesize in human readable way.
*
* @param file $file
* @return string Formatted Filesize, e.g. "113.24 MB".
*/
function filesize_formatted($file)
{
$bytes = filesize($file);
if ($bytes >= 1073741824) {
return number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
return number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
return number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
return $bytes . ' bytes';
} elseif ($bytes == 1) {
return '1 byte';
} else {
return '0 bytes';
}
}
回答by Bat Fung
This would be a cleaner implementation:
这将是一个更清晰的实现:
function size2Byte($size) {
$units = array('KB', 'MB', 'GB', 'TB');
$currUnit = '';
while (count($units) > 0 && $size > 1024) {
$currUnit = array_shift($units);
$size /= 1024;
}
return ($size | 0) . $currUnit;
}
回答by miyuru
All the answers to the question uses that 1 kilobyte = 1024 bytes which is wrong! (1 kibibyte = 1024 bytes)
该问题的所有答案都使用 1 KB = 1024 字节,这是错误的!(1 kibibyte = 1024 字节)
since the question asks to convert file sizes, it should use that 1 kilobyte = 1000 bytes(see https://wiki.ubuntu.com/UnitsPolicy)
由于问题要求转换文件大小,因此应使用1 KB = 1000 字节(请参阅https://wiki.ubuntu.com/UnitsPolicy)
function format_bytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1000));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1000, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
回答by Yogi Ghorecha
Here is a simple function to convert Bytes to KB, MB, GB, TB :
这是一个将 Bytes 转换为 KB, MB, GB, TB 的简单函数:
# Size in Bytes
$size = 14903511;
# Call this function to convert bytes to KB/MB/GB/TB
echo convertToReadableSize($size);
# Output => 14.2 MB
function convertToReadableSize($size){
$base = log($size) / log(1024);
$suffix = array("", "KB", "MB", "GB", "TB");
$f_base = floor($base);
return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
回答by vdbuilder
A complete example.
一个完整的例子。
<?php
$units = explode(' ','B KB MB GB TB PB');
echo("<html><body>");
echo('file size: ' . format_size(filesize("example.txt")));
echo("</body></html>");
function format_size($size) {
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>
回答by Hamed
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;
}