How to get file sizes KB, MB & GB using PHP

Here’s the follow-up article on how to easily get file sizes nicely formatted. Below is a quick function that will display the file size in KB, MB, or GB all easily accessed through a function. You may also like How to convert bytes Into KB, MB and GB using PHP and PHP sizeof() Function.


    $filw_size =  filesize($file); 
    $fsize =  getfilesize($filw_size, 2);

    function getfilesize($bytes, $decimals = 2)
        if ($bytes < 1024) {
            return $bytes . ' B';

        $factor = floor(log($bytes, 1024));
        return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][$factor];

Leave a Reply

Your email address will not be published. Required fields are marked *