11 Vote

PHP: Show File Size with B, kB, MB, GB or TB Unit

Tutorial by Progger99 | 2014-06-23 at 14:41

Today, I would like to introduce a function with which it is possible to display the size of a file in PHP.

The function takes care about using the correct fitting unit for the appropriate filesize such as kB or MB and optionally, you can specify the number of decimal places you would like to use.

function show_filesize($filename, $decimalplaces = 0) {

  $size = filesize($filename);
  $sizes = array('B', 'kB', 'MB', 'GB', 'TB');

  for ($i=0; $size > 1024 && $i < count($sizes) - 1; $i++) {
     $size /= 1024;
  }
  return round($size, $decimalplaces).' '.$sizes[$i];

}

You can use the function like that, for example:

echo show_filesize('text.txt');     // 12 kB
echo show_filesize('text.txt', 3);  // 12.345 kB
echo show_filesize('bigdata.txt');  // 89 TB

The first parameter we have to pass to the function is the file name/file path. The second parameter is optional and can be left. It can be used to adjust the number of decimal places.

By default, the decimal places are 0 here, but you can also adjust this in the function above ($decimalplaces = 0). You can also extend or rewrite the array $sizes if you would like to use other or more units.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

PHPExcel: Change Font Size

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.