Calculate (convert) File Size


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

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.