format filesize as bytes kilobyte megabyte kb-mb-gb ending in php

PHP Add comments

I want to format a filesize in php as either of these bytes, kilobytes, megabytes, gigabytes according to the size of the file.

I found the following codes in php.net comments section

I just copied the following code as it was in the source and i have use only one and not the others.

You can better directly do this url to see the updated function or try the following functions.

You can find these below the documentation of filesize function. (The comments section of the document).

function FileSize($file, $setup = null)
{
    $FZ = ($file && @is_file($file)) ? filesize($file) : NULL;
    $FS = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
 
    if(!$setup && $setup !== 0)
    {
        return number_format($FZ/pow(1024, $I=floor(log($FZ, 1024))), ($i >= 1) ? 2 : 0) . ' ' . $FS[$I];
    } elseif ($setup == 'INT') return number_format($FZ);
    else return number_format($FZ/pow(1024, $setup), ($setup >= 1) ? 2 : 0 ). ' ' . $FS[$setup];
}

Here is another one

 
function format_bytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

and yet the simplest one as mentioned in the docs

 
function format_bytes($bytes) {
   if ($bytes < 1024) return $bytes.' B';
   elseif ($bytes < 1048576) return round($bytes / 1024, 2).' KB';
   elseif ($bytes < 1073741824) return round($bytes / 1048576, 2).' MB';
   elseif ($bytes < 1099511627776) return round($bytes / 1073741824, 2).' GB';
   else return round($bytes / 1099511627776, 2).' TB';
}

besides, the document said

It’s very interesting but I can’t stand the decimals for bytes and KB so here’s another example :

 
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), $i > 1 ? 2 : 0) . $sizes[$i]); }
}

and then another contributor said

This is a short and very clever function to get filesizes.

 
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}

and it goes on like the above in http://php.net

Reference

http://php.net/manual/en/function.filesize.php

Scroll the page down to see as many as function like the above and suite yourself.

Enjoy.

Leave a Reply

Entries RSS