Calculate human readable file size

Information for PHP. Hypertext Preprocessor
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

Calculate human readable file size

Post by dzcadii » Sat Mar 14, 2015 11:32 pm

I put this in a class but you can just take it out for its own function

Code: Select all

<?PHP
class FileSystemHelper
{
    public function GetHumanReadableFileSize($bytes, $precision = 2)
    {  
        $kilobyte = 1024;
        $megabyte = $kilobyte * 1024;
        $gigabyte = $megabyte * 1024;
        $terabyte = $gigabyte * 1024;
       
        if (($bytes >= 0) && ($bytes < $kilobyte)) {
            return $bytes . ' B';
     
        } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
            return round($bytes / $kilobyte, $precision) . ' KB';
     
        } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
            return round($bytes / $megabyte, $precision) . ' MB';
     
        } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
            return round($bytes / $gigabyte, $precision) . ' GB';
     
        } elseif ($bytes >= $terabyte) {
            return round($bytes / $terabyte, $precision) . ' TB';
        } else {
            return $bytes . ' B';
        }
    }
}
usage:

Code: Select all

<?PHP
$fileSize = "123456789010";
$fileSystemHelper = new FileSystemHelper();
$humanFSize = $humanFSize->fileSystemHelper($fileSize);
echo $humanFSize;
?>

Post Reply