Convert bytes to MB, GB, TB and PB with PHP

August 11, 2011
A simple PHP function to convert bytes to the rounded megabyte, gigabyte, terabyte, and petabyte amounts.

Note that petabytes are not currently supported, not because of the function, but because of the maximum signed integer size in PHP.

P.S. This page has a very, very, very long URL.

Download Original
  1. <?PHP
  2. function bytes2English($filesize)
  3. {
  4. if ($filesize<1048676)
  5. RETURN number_format($filesize/1024,1) . " KB";
  6. if ($filesize>=1048576 && $filesize<1073741824)
  7. RETURN number_format($filesize/1048576,1) . " MB";
  8. if ($filesize>=1073741824 && $filesize<1099511627776)
  9. RETURN number_format($filesize/1073741824,2) . " GB";
  10. if ($filesize>=1099511627776)
  11. RETURN number_format($filesize/1099511627776,2) . " TB";
  12. if ($filesize>=1125899906842624) //Currently, PB won't show due to PHP limitations
  13. RETURN number_format($filesize/1125899906842624,3) . " PB";
  14. }
  15. echo bytes2english(59417665);
  16. ?>
Name:

No comments yet! Be the first!