Categories: PHP

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&#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!

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.

View Comments

  • 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.

Recent Posts

Free GG Mug Mockup

GG Mug Mockup designed for logo branding of companies and brands.

6 years ago

Lovtony Font Duo – Modern Sans Serif

A great font/script for creating beautiful logos, posters, wedding invitations, blog posts, social media, and…

6 years ago

Free Men T-Shirt Mockup

Realistic T-Shirt Mockup PSD which you can use freely to showcase your apparel design.

6 years ago

Classic Coffee Mug Mock-up Free PSD

Classic coffee mug Mock-up Free PSD. Free mug mockup PSD to showcase your branding design…

6 years ago

Juliette – Stylish Handwritten Signature Font

Juliette - Stylish Handwritten Signature Font

6 years ago

XXII Aven Sans Serif Font Family

XXII Aven Font Family - a new modern all-caps sans serif font with versatility in creativity.

6 years ago