PHP - Size converter


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Get the human-readable size for an amount of bytes
  3.  * @param int $size : the number of bytes to be converted
  4.  * @param int $precision : number of decimal places to round to;
  5.  * optional - defaults to 2
  6.  * @param bool $long_name : whether or not the returned size tag should
  7.  * be unabbreviated (ie "Gigabytes" or "GB");
  8.  * optional - defaults to true
  9.  * @param bool $real_size : whether or not to use the real (base 1024)
  10.  * or commercial (base 1000) size;
  11.  * optional - defaults to true
  12.  * @return string : the converted size
  13.  */
  14. function get_size($size,$precision=2,$long_name=true,$real_size=true) {
  15. $base=$real_size?1024:1000;
  16. $pos=0;
  17. while ($size>$base) {
  18. $size/=$base;
  19. $pos++;
  20. }
  21. $prefix=get_size_prefix($pos);
  22. $size_name=$long_name?$prefix."bytes":$prefix[0].'B';
  23. return round($size,$precision).' '.ucfirst($size_name);
  24. }
  25. /**
  26.  * @param int $pos : the distence along the metric scale relitive to 0
  27.  * @return string : the prefix
  28.  */
  29. function get_size_prefix($pos) {
  30. switch ($pos) {
  31. case 00: return "";
  32. case 01: return "kilo";
  33. case 02: return "mega";
  34. case 03: return "giga";
  35. case 04: return "tera";
  36. case 05: return "peta";
  37. case 06: return "exa";
  38. case 07: return "zetta";
  39. case 08: return "yotta";
  40. case 09: return "xenna";
  41. case 10: return "w-";
  42. case 11: return "vendeka";
  43. case 12: return "u-";
  44. default: return "?-";
  45. }
  46. }

URL: http://www.roscripts.com/snippets/show/188

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.