Reputation: 43
I want to be able to take a file and only display it in megabytes. So for example, if I were to have a file that is only 120kb or 2mb, I want it to echo it out as 0.12mb and 2mb respectively.
Below is the code that I currently have and hoping if someone can help?
<?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;
?>
Thank you.
Upvotes: 3
Views: 5173
Reputation: 1131
Here it is mate:
<?php
function convert_to_mb($size)
{
$mb_size = $size / 1048576;
$format_size = number_format($mb_size, 2) . ' MB';
return $format_size;
}
?>
Upvotes: 1
Reputation: 405
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);
}
With this function you can do what you want:
sizeFormat('120', 'MB');
Upvotes: 1
Reputation: 1154
just divide by 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;
?>
Upvotes: 5