1
0

formating-bytes.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2012 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * convert given bytes into human readable string
  15. * @author banana mail@bananas-playground.net
  16. * @author Guillaume Amringer g.amringer@gmail.com
  17. *
  18. * @param int $amount Bytes
  19. * @param string $unit
  20. * @param int $decimals
  21. * @param int $powerMax
  22. * @param boolean $binary
  23. * @param int $powerBase
  24. * @return string Human readable format
  25. */
  26. function unit($amount, $unit, $decimals = 2, $powerMax = 100, $binary = true, $powerBase = 0) {
  27. if ($binary) {
  28. $powerBase = $powerBase == 0 ? 1024 : $powerBase;
  29. $prefixes = array('','Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi');
  30. } else {
  31. $powerBase = $powerBase == 0 ? 1000 : $powerBase;
  32. $prefixes = array('','K','M','G','T','P','E','Z','Y');
  33. }
  34. $power = 0;
  35. while($amount > $powerBase && $power < $powerMax) {
  36. $power++;
  37. $amount /= $powerBase;
  38. }
  39. return round($amount, $decimals) . ' ' . $prefixes[$power] . $unit;
  40. }
  41. ?>