Posted By

kirik on 08/21/09


Tagged

file size byte convert calculate mb kb gb tb


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

maxvee8
umang_nine
IMPGTX


Calculate (convert) File Size


 / Published in: PHP
 

This function converts file size in bytes to the larger units. You can add bigger values like exa-, zetta-, yotta- bytes.

  1. function calculateSize($size, $sep = ' ')
  2. {
  3. $unit = null;
  4. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  5.  
  6. for($i = 0, $c = count($units); $i < $c; $i++)
  7. {
  8. if ($size > 1024)
  9. {
  10. $size = $size / 1024;
  11. }
  12. else
  13. {
  14. $unit = $units[$i];
  15. break;
  16. }
  17. }
  18.  
  19. return round($size, 2).$sep.$unit;
  20. }
  21. echo calculateSize(32942443); // Result: 31.42 MB
  22. echo calculateSize(2298543567223, ''); // Result: 2.09TB

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: richblood on February 6, 2013

Good job, thank you.

You need to login to post a comment.