Posted By

section31 on 03/03/07


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

basicmagic
vali29


Size Readable


 / Published in: PHP
 

  1. <?php
  2. /**
  3. * Return human readable sizes
  4. *
  5. * @author Aidan Lister <[email protected]>
  6. * @version 1.1.0
  7. * @link http://aidanlister.com/repos/v/function.size_readable.php
  8. * @param int $size Size
  9. * @param int $unit The maximum unit
  10. * @param int $retstring The return string format
  11. * @param int $si Whether to use SI prefixes
  12. */
  13. function size_readable($size, $unit = null, $retstring = null, $si = true)
  14. {
  15. // Units
  16. if ($si === true) {
  17. $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
  18. $mod = 1000;
  19. } else {
  20. $sizes = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
  21. $mod = 1024;
  22. }
  23. $ii = count($sizes) - 1;
  24.  
  25. // Max unit
  26. $unit = array_search((string) $unit, $sizes);
  27. if ($unit === null || $unit === false) {
  28. $unit = $ii;
  29. }
  30.  
  31. // Return string
  32. if ($retstring === null) {
  33. $retstring = '%01.2f %s';
  34. }
  35.  
  36. // Loop
  37. $i = 0;
  38. while ($unit != $i && $size >= 1024 && $i < $ii) {
  39. $size /= $mod;
  40. $i++;
  41. }
  42.  
  43. return sprintf($retstring, $size, $sizes[$i]);
  44. }
  45.  
  46. ?>

Report this snippet  

You need to login to post a comment.