Convert Bytes to corresponding size


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

Takes a number in bytes and returns the number in (KB,MB,GB) for human-readable format.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function ByteSize($bytes)
  4. {
  5. $size = $bytes / 1024;
  6. if($size < 1024)
  7. {
  8. $size = number_format($size, 2);
  9. $size .= ' KB';
  10. }
  11. else
  12. {
  13. if($size / 1024 < 1024)
  14. {
  15. $size = number_format($size / 1024, 2);
  16. $size .= ' MB';
  17. }
  18. else if ($size / 1024 / 1024 < 1024)
  19. {
  20. $size = number_format($size / 1024 / 1024, 2);
  21. $size .= ' GB';
  22. }
  23. }
  24. return $size;
  25. }
  26.  
  27. // Returns '19.28mb'
  28. print ByteSize('20211982');
  29.  
  30. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.