PHP Function: format_filesize()

This function allows you to make user readable filesizes easily.
Example: ’1024′ into ’1Kb’.


Format your file sizes from bytes to megabytes or kilobytes etc.

The function/code:

function format_size($bytes,$d=2) {
    $bytes = max(0, (int) $bytes);
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    return sprintf("%01.{$d}f%s",($bytes / pow(1024, floor(log($bytes, 1024)))),$units[floor(log($bytes, 1024))]);
}

The examples:

echo format_size(211128); // Outputs: 206.18Kb
echo format_size(10240000); // Outputs: 9.77Mb
echo format_size(10245,0); // Ouputs: 10Kb (No decimals)

I’d be interested to know who uses this snippet =)

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

Try this…

echo format_size(11111111111,0);

you will get this…

Warning: Division by zero in C:\AppServ\www\format_size.php on line 7
0B

need some retouch…

My correction of this function. Now there is no problem with 0 and with big numbers:

function format_size($bytes,$d=3) {
$bytes = max(0, (float) $bytes);
$units = array(‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’, ‘PB’);
if ($bytes!=0)
return sprintf(“%01.{$d}f%s”,($bytes / pow(1024, floor(log($bytes, 1024)))),$units[floor(log($bytes, 1024))]);
else
return “0 bytes”;
}

Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru

Leave a comment

(required)

(required)