Breaking News
Home / Web / PHP / PHP Snippets / How to convert bytes into human readable string format in PHP?

How to convert bytes into human readable string format in PHP?

Snippet

  1. //////////////////////////////////////////////////
  2. //  formatBytes($file_size) mixed file sizes
  3. //  formatBytes($file_size, 0) KB file sizes
  4. //  formatBytes($file_size, 1) MB file sizes etc
  5. //////////////////////////////////////////////////
  6. function formatBytes($bytes, $format = 99) {
  7. $byte_size = 1024;
  8.     $byte_type = array(" KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  9.  
  10.     $bytes /= $byte_size;
  11.     $i = 0;
  12.  
  13.     if ($format == 99 || $format > 7) {
  14.       while ($bytes > $byte_size) {
  15.             $bytes /= $byte_size;
  16.             $i++;
  17.         }
  18.     } else {
  19.       while ($i < $format) {
  20.             $bytes /= $byte_size;
  21.             $i++;
  22.         }
  23.     }
  24.  
  25.     $bytes = sprintf("%1.2f", $bytes);
  26.     $bytes .= $byte_type[$i];
  27.  
  28.     return$bytes;
  29. }

<!>

[pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Leave a Reply