How to format bytes to kilobytes, megabytes, gigabytes and terabytes in PHP

2 Answers

0 votes
function FormatBytes($bytes) {
    $sizes = array("B", "KB", "MB", "GB", "TB");
  
    $dblByte = $bytes;
    for ($i = 0; $i < count($sizes) && $bytes >= 1024; $i++, $bytes /= 1024) {
         $dblByte = $bytes / 1024.0;
    }
              
    return round($dblByte, 2) . " " . $sizes[$i];
}
  
echo FormatBytes(9823453784599) . "\n";
echo FormatBytes(7124362542) . "\n";
echo FormatBytes(23746178) . "\n";
echo FormatBytes(1048576) . "\n";
echo FormatBytes(1024000) . "\n";
echo FormatBytes(873445) . "\n";
echo FormatBytes(1024) . "\n";
echo FormatBytes(978) . "\n";
echo FormatBytes(13) . "\n";
echo FormatBytes(0) . "\n";
 
 
 
/*
run: 
 
8.93 TB
6.64 GB
22.65 MB
1 MB
1000 KB
852.97 KB
1 KB
978 B
13 B
0 B
 
*/

 



answered Apr 23, 2016 by avibootz
edited Apr 14, 2024 by avibootz
0 votes
function formatBytes($bytes, $precision = 2) {
    if  ($bytes == 0) {
        return '0 B';
    }
    
    $sizes = array('B', 'KB', 'M', 'GB', 'TB');   
    $base = log($bytes, 1024);
 
    return round(pow(1024, $base - floor($base)), $precision) . ' ' . $sizes[floor($base)];
}
  
echo FormatBytes(9823453784599) . "\n";
echo FormatBytes(7124362542) . "\n";
echo FormatBytes(23746178) . "\n";
echo FormatBytes(1048576) . "\n";
echo FormatBytes(1024000) . "\n";
echo FormatBytes(873445) . "\n";
echo FormatBytes(1024) . "\n";
echo FormatBytes(978) . "\n";
echo FormatBytes(13) . "\n";
echo FormatBytes(0) . "\n";
 
 
 
/*
run: 
 
8.93 TB
6.64 GB
22.65 M
1 M
1000 KB
852.97 KB
1 KB
978 B
13 B
0 B
 
*/

 



answered Apr 14, 2024 by avibootz
...