Quantcast
Channel: Phil's Blog » php
Viewing all articles
Browse latest Browse all 10

PHP – Converting bytes to a readable format

$
0
0

The following function takes in a number of bytes and the number of decimal places required in the output and returns the result in a readable format:

  1. function readable_filesize($bytes, $dp = 1) {
  2. // Extensions used
  3. $extensions = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  4.  
  5. foreach ($extensions as $ext) {
  6. // If we can't divide again without getting < 1
  7. if ($bytes < 1024) {
  8. return number_format($bytes, $dp).$ext;
  9. }
  10.  
  11. $bytes /= 1024;
  12. }
  13.  
  14. // If we're here, we're at the end of the extensions array
  15. // thus return what we have
  16. return $bytes.$ext;
  17. }

Use like this:

  1. echo readable_filesize(123456);

 


Viewing all articles
Browse latest Browse all 10

Trending Articles