Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

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

$
0
0

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. }

<!--break-->


Viewing all articles
Browse latest Browse all 178

Trending Articles