PHP Filesize Formats

March 29, 2009

This handy function allows you to pass a filesize in bytes and have it returned with the appropriate suffix.

Credit is due, but I don’t remember where I originally found it (possibly the PHP documentation site).

<?php
function filesize_format ($bytes)
{
    if ($bytes > 0)
    {
        $suffixes = array('B', 'KB', 'MB', 'GB', 'TB');
        $bytes = (int) $bytes;

        $bits = 1024;
        $result = (int) (log($bytes, $bits));

        return round($bytes / pow($bits, $result)).' '.$suffixes[$result];
    }
    else
    {
        return '0 B';
    }
}
comments powered by Disqus