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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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: <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!

PHP # ,
Share: / / /

You might also like

0 thoughts on “Calculate folder and subfolders size with PHP

  1. Dina Dadian says:

    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.

  2. abha says:

    Undefined variable: retstring

  3. abha says:

    $retstring = ‘%01.2f %s’;

Leave a Reply

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