Grow your CSS skills. Land your dream job.

Last updated on:

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;
}

Comments

  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;
    }
    
    ?>

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".