Posted By

jatkins on 04/27/11


Tagged

file size humanize parser


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

sbcjr
beleneglorion


Humanize file size


 / Published in: PHP
 

Released into the public domain. Append $unit_sizes_bytes as you wish to allow for terabytes, petabytes, etc. (if you need that) -- each array item is an array item with the first value being the symbol for the unit and the second item being the minimum value of any file that is at least 1x that unit.

  1. function humanize_file_size($size_in_bytes) {
  2. $size_in_bytes = preg_replace('/[^0-9\.\-]/', '', $size_in_bytes); // clean
  3. if($size_in_bytes!=''&&strpos($size_in_bytes, '-')===false) {
  4. if(round((int) $size_in_bytes)==0)
  5. return '0 B';
  6. else {
  7. $size_in_bytes = (float) $size_in_bytes;
  8. $unit_sizes_bytes = array(array('B', 1), array('kB', 1024), array('MB', 1048576), array('GB', 1073741824));
  9. $finished = 0;
  10. for($i=0;$i<count($unit_sizes_bytes);$i++) {
  11. if($size_in_bytes>=$unit_sizes_bytes[$i][1]&&(!isset($unit_sizes_bytes[$i+1])||(isset($unit_sizes_bytes[$i+1])&&$size_in_bytes<$unit_sizes_bytes[$i+1][1]))) {
  12. $finished = 1;
  13. return round(($size_in_bytes / $unit_sizes_bytes[$i][1])*100)/100 . ' ' . $unit_sizes_bytes[$i][0];
  14. break;
  15. }
  16. }
  17. $last_unit = $unit_sizes_bytes[count($unit_sizes_bytes)];
  18. if($finished==0)
  19. return $size_in_bytes >= $last_unit[1] ? round(($size_in_bytes / $last_unit[1])*100)/100 . ' ' . $last_unit[0] : round($size_in_bytes) . ' B';
  20. }
  21. }
  22. else
  23. return 'N/A';
  24. }

Report this snippet  

You need to login to post a comment.