如何使用PHP将文件大小转换为仅兆字节
我希望能够获取一个文件,并仅以兆字节为单位显示它。举个例子,如果我有一个只有120kb或2mb的文件,我希望它分别以0.12mb和2mb的大小进行回传 下面是我目前拥有的代码,希望有人能帮助我如何使用PHP将文件大小转换为仅兆字节,php,html,Php,Html,我希望能够获取一个文件,并仅以兆字节为单位显示它。举个例子,如果我有一个只有120kb或2mb的文件,我希望它分别以0.12mb和2mb的大小进行回传 下面是我目前拥有的代码,希望有人能帮助我 <?php function byte_convert($size) { # size smaller then 1kb if ($size < 1024) return $size . ' Byte'; # size smaller then 1m
<?php
function byte_convert($size) {
# size smaller then 1kb
if ($size < 1024) return $size . ' Byte';
# size smaller then 1mb
if ($size < 1048576) return sprintf("%4.2f KB", $size/1024);
# size smaller then 1gb
if ($size < 1073741824) return sprintf("%4.2f MB", $size/1048576);
# size smaller then 1tb
if ($size < 1099511627776) return sprintf("%4.2f GB", $size/1073741824);
# size larger then 1tb
else return sprintf("%4.2f TB", $size/1073741824);
}
$file_path = "pic1.jpg";
$file_size = byte_convert(filesize($file_path));
echo $file_size;
?>
谢谢。这是大副:
<?php
function convert_to_mb($size)
{
$mb_size = $size / 1048576;
$format_size = number_format($mb_size, 2) . ' MB';
return $format_size;
}
?>
只需除以1024*1024即可
<?php
function get_mb($size) {
return sprintf("%4.2f MB", $size/1048576);
}
$file_path = "pic1.jpg";
$file_size = get_mb(filesize($file_path));
echo $file_size;
?>
FYI:兆字节(MB)是10^6(1000 000)字节,兆字节(MiB)是2^20(1048 576)字节。请帮我一个忙,使用MiB好吗?非常好,谢谢你,现在我只需在echo语句中做一行代码,就像这样
”。sizeFormat(文件大小($dir./'.$file),'MB')。
function sizeFormat($bytes, $unit = "", $decimals = 2) {
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes)/log(1024));
$unit = array_search($pow, $units);
}
$value = ($bytes/pow(1024,floor($units[$unit])));
}
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
return sprintf('%.' . $decimals . 'f '.$unit, $value);
}
sizeFormat('120', 'MB');