Those days i was wondering whether i could read the size of a directory using PHP. So i thought of making something which could help me read the size of the directory, number of directories and the number of files in the given directory.

So here are my 2 little functions doing that bit:

The function “filesize_recursive” will ignore link/shortcuts to files/directory.
The function “display_size” will suffix the size with bytes, KB, MB or GB accordingly.


< ?php
$path = "/path-to-folder"; // <-- Edit: Add your folder name here!
 
function filesize_recursive($path){ // Function 1
if(!file_exists($path)) return 0;
if(is_file($path)) return filesize($path);
$ret = 0;
foreach(glob($path."/*") as $fn)
$ret += filesize_recursive($fn);
return $ret;
}
 
function display_size($size) { // Function 2
$sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        if ($retstring === null) { $retstring = '%01.2f %s'; }
        $lastsizestring = end($sizes);
        foreach ($sizes as $sizestring) {
        	if ($size < 1024) { break; }
            if ($sizestring != $lastsizestring) { $size /= 1024; }
        	}
        if ($sizestring == $sizes&#91;0&#93;) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
        return sprintf($retstring, $size, $sizestring);
}
 
echo "Folder {$path} size: <b>".display_size(filesize_recursive($path))."";
?>

Depending on the size of a folder, is it possible to display the size value in MegaBytes, GigaBytes, or TeraBytes, including the appropriate abbreviations MB, GB, TB, etc ..

Enjoy!

0 Shares:
3 comments
  1. Jecklin, thank you for a pain-free code. I googled “php calculate size folder and subfolders” and among several other results I tried, your post was the only one that worked on cut and paste, without debugging for broken syntax. Perfect! Thanks from New Jersey.

Leave a Reply

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

8 + five =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

Genghis – A Single File MongoDB Admin

In order to manage MongoDB databases easily, Genghis, a single-file, self-hosted and web-based solution is pretty handy. It can be installed either as a Ruby gem or as a standalone PHP script.