Human Readable File Size with PHP

Here’s a nice and simple function to get a human readable file size in PHP:

<?php
function human_filesize($bytes, $decimals = 2) {
    $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

for example:

<?php
echo human_filesize(filesize('example.zip'));

may echo 42.64MB.