The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Implementing an SVG Icon System" Nov 30 - 6:00 PM Eastern

Get File Size

Last updated on:
 * @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;


  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)

     * @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:

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

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed