Search code examples
phpfilefilesize

PHP filesize MB/KB conversion


How can I convert the output of PHP's filesize() function to a nice format with MegaBytes, KiloBytes etc?

like:

  • if the size is less than 1 MB, show the size in KB
  • if it's between 1 MB - 1 GB show it in MB
  • if it's larger - in GB

Solution

  • Here is a sample:

    <?php
    // Snippet from PHP Share: http://www.phpshare.org
    
        function formatSizeUnits($bytes)
        {
            if ($bytes >= 1073741824)
            {
                $bytes = number_format($bytes / 1073741824, 2) . ' GB';
            }
            elseif ($bytes >= 1048576)
            {
                $bytes = number_format($bytes / 1048576, 2) . ' MB';
            }
            elseif ($bytes >= 1024)
            {
                $bytes = number_format($bytes / 1024, 2) . ' KB';
            }
            elseif ($bytes > 1)
            {
                $bytes = $bytes . ' bytes';
            }
            elseif ($bytes == 1)
            {
                $bytes = $bytes . ' byte';
            }
            else
            {
                $bytes = '0 bytes';
            }
    
            return $bytes;
    }
    ?>