Code Snippet

Home » Code Snippets » PHP » Get File Size

Get File Size

/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function getFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}

Subscribe to The Thread

  1. Jordan Pittman

    I find this function to be a good bit faster. (If you remove realpath it will shave an extra ~8 seconds over 100,000 iterations)

    <?php
    /*
     * @param string $file File name or path to a file
     * @param int $precision Digits to display after decimal
     * @return string|bool Size (B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB) or boolean
     */
    
    function getFileSize($file, $precision = 2) {
    	static $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
    
    	if (is_file($file)) {
    		if (!realpath($file)) $file = $_SERVER['DOCUMENT_ROOT'] . $file;
    		$fileSize = filesize($file);
    
    		// hardcoded maximum number of units @ 9 for minor speed increase
    		$power = max(floor(log($fileSize, 1024)), 8);
    		return round($fileSize / pow(1024, $power), $precision) . $units[$power];
    	}
    	return false;
    }
    
    ?>

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~