How to get file sizes KB, MB & GB using PHP
Here’s the follow-up article on how to easily get file sizes nicely formated. Below is a quick function that will display the file size in KB, MB, or GB all easily accessed through a function.
Code
<?php
$filw_size = filesize($file);
$fsize = getfilesize($filw_size, 2);
function getfilesize($bytes, $decimals = 2)
{
if ($bytes < 1024) {
return $bytes . ' B';
}
$factor = floor(log($bytes, 1024));
return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][$factor];
}
?>
Leave a Reply