Nov
24
2011

Calculate folder and subfolders size with PHP

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[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
return sprintf($retstring, $size, $sizestring);
}

echo "Folder {$path} size: ".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!

About the Author: SGH

At the same time, I can’t think of anything more satisfying than sitting in front of TV, eating take-away, lights down low, in my pyjamas and watching crap on TV. Basically, I strive to live a balanced life. Fun. Serious. Fast. Slow. Brainy. Bimbotic. Intense. Lazy. You get the drift.

3 Comments: + Add Comment

  • $retstring = '%01.2f %s';
  • Undefined variable: retstring
  • 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 comment

Click to refresh

Subscribe to newsletter

Sign up with your email to get updates about new resources releases and special offers.