Convert size in bytes to a human readable format (PHP)

Another day and another function. This time a function, which converts size in bytes to a human readable format. For example, 1024 will become "1KB", but 1048576 will become "1MB".

You can also specify the precision that you want the number to formated with. For example, if $bytes variable was originally 1,000,000 bytes then the result would be "976.56 KB" if the precision set to 2 or "976 KB" if set to 0.

As you can see the function is pretty straightforward - we determine in which range the number is, divide the original amount with the appropriate number and append the unit of measure:

  1. <?php
  2.  
  3. /**
  4.  * Convert bytes to human readable format
  5.  *
  6.  * @param integer bytes Size in bytes to convert
  7.  * @return string
  8.  */
  9. function bytesToSize($bytes, $precision = 2)
  10. {  
  11.     $kilobyte = 1024;
  12.     $megabyte = $kilobyte * 1024;
  13.     $gigabyte = $megabyte * 1024;
  14.     $terabyte = $gigabyte * 1024;
  15.    
  16.     if (($bytes >= 0) && ($bytes < $kilobyte)) {
  17.         return $bytes . ' B';
  18.  
  19.     } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
  20.         return round($bytes / $kilobyte, $precision) . ' KB';
  21.  
  22.     } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
  23.         return round($bytes / $megabyte, $precision) . ' MB';
  24.  
  25.     } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
  26.         return round($bytes / $gigabyte, $precision) . ' GB';
  27.  
  28.     } elseif ($bytes >= $terabyte) {
  29.         return round($bytes / $terabyte, $precision) . ' TB';
  30.     } else {
  31.         return $bytes . ' B';
  32.     }
  33. }

As you know:

  • 1 kilobyte = 1024 bytes
  • 1 megabyte = 1024 kilobytes = 1,048,576 bytes
  • 1 gigabyte = 1024 megabytes = 1,048,576 kilobytes = 1,073,741,824 bytes
  • 1 terabyte = 1024 gigabytes = 1,048,576 megabytes = 1,073,741,824 kilobytes = 1,099,511,627,776 bytes

Knowing this we can easily calculate values of $kilobyte, $megabyte, $gigabyte and $terabyte variables multiplying the previous measurement by 1024.

If the size in bytes is in none of the ranges then we simply return the original number as it means that it is larger than terabyte.

You can also find the JavaScript implementation of this function in article Convert size in bytes to human readable format (JavaScript).

Comments
1
//
// php.net has examples of this which are nice as well.
//
// PHP: log - Manual
// PHP: memory_get_usage - Manual
//
function bytesToSize1000($bytes, $precision = 2)
{
    // human readable format -- powers of 1000
    //
    $unit = array('b','kb','mb','gb','tb','pb','eb');

    return @round(
        $bytes / pow(1000, ($i = floor(log($bytes, 1000)))), $precision
    ).' '.$unit[$i];
}
function bytesToSize1024($bytes, $precision = 2)
{
    // human readable format -- powers of 1024
    //
    $unit = array('B','KB','MB','GB','TB','PB','EB');

    return @round(
        $bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision
    ).' '.$unit[$i];
}
Mario, May 17th 2010, 22:57
2
You have a bug in the code.  You divide by $gigabyte twice and call the second one TB.
C, December 2nd 2010, 23:51
3
Thanks, C! Fixed.
Andris, December 8th 2010, 14:20
4
Thanks for the info
Soffian, September 16th 2011, 17:32
5
You script is GOOD, not have any error ;D
Isael, April 7th 2013, 12:46
6
How I can call it?

Example I have data in database : 

$id = $_GET['id'];

$query = "SELECT * FROM document where id_document = '".$id."'"; 
$result = mysql_query($query) or die(mysql_error());
$r = mysql_fetch_array($result) or die(mysql_error());

$bytes = $r["size"];


function bytesToSize($bytes, $precision = 2)
{  
    $kilobyte = 1024;
    $megabyte = $kilobyte * 1024;
    $gigabyte = $megabyte * 1024;
    $terabyte = $gigabyte * 1024;
   
    if (($bytes >= 0) && ($bytes < $kilobyte)) {
        return $bytes . ' B';
 
    } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
        return round($bytes / $kilobyte, $precision) . ' KB';
 
    } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
        return round($bytes / $megabyte, $precision) . ' MB';
 
    } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
        return round($bytes / $gigabyte, $precision) . ' GB';
 
    } elseif ($bytes >= $terabyte) {
        return round($bytes / $terabyte, $precision) . ' TB';
    } else {
        return $bytes . ' B';
    }
}



echo "<b>" .$r['title']. " (";
echo "" .bytesToSize();
echo ")</b><br /><u>Decription:</u><br />";
echo $r['abtract'];

the result only show "title" ( B).
Please need help.

Thank you
prazetyo, April 18th 2013, 2:29
7
You haven't passed the size field to the function. Change your second line to this and it will work:
echo bytesToSize($bytes);

The bytesToSize function won't "see" your $bytes variable, even though you define it before the function declaration. It's a totally different scope. Have a look at this page for more information on scopes: PHP: Variable scope - Manual
Andris, May 6th 2013, 19:04
8
With the following method you have some more customization options:


    public function formatBytes($size,$level=0,$precision=2,$base=1024) 
    {
        $unit = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB','YB');
        $times = floor(log($size,$base));
        return sprintf("%.".$precision."f",$size/pow($base,($times+$level)))." ".$unit[$times+$level];
    }
Peter, April 20th 2014, 14:38
9
Thank you for the great codes!
woody, June 18th 2015, 17:01
10
@Mario I don't like the shorter code BTW, be human readable:)
woody, June 18th 2015, 17:03
11
I've found this:

function format_filesize($B, $D=2){
    $S = 'BKMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F].'b';
}
alec, October 2nd 2015, 19:11
12
Смотрите лучше здесь:
ландшафтный дизайн (Maxine)
https://goo.gl/HpJx3v
Maxine, May 19th 2017, 10:07
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments