Treehouse: 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

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```