Get Folder Size in PHP


Most of the web hosting company does not provide unlimited FTP spaces. In order to monitor the usage, you can login to web-based control panel and view the usage statistics.

Another handy method would be to use PHP to compute the folder sizes. The following is a function to recursively compute the size in bytes for a web-folder. Of course, base on this function, you can easily create events of notification (such as sending emails when usage is high).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    function dirsize($dir)
    {
      @$dh = opendir($dir);
      $size = 0;
      while ($file = @readdir($dh))
      {
        if ($file != "." and $file != "..") 
        {
          $path = $dir."/".$file;
          if (is_dir($path))
          {
            $size += dirsize($path); // recursive in sub-folders
          }
          elseif (is_file($path))
          {
            $size += filesize($path); // add file
          }
        }
      }
      @closedir($dh);
      return $size;
    }
    function dirsize($dir)
    {
      @$dh = opendir($dir);
      $size = 0;
      while ($file = @readdir($dh))
      {
        if ($file != "." and $file != "..") 
        {
          $path = $dir."/".$file;
          if (is_dir($path))
          {
            $size += dirsize($path); // recursive in sub-folders
          }
          elseif (is_file($path))
          {
            $size += filesize($path); // add file
          }
        }
      }
      @closedir($dh);
      return $size;
    }

Another simpler solution from realmag777 that utilities the latest PHP language feature:

1
2
3
4
5
6
7
8
9
10
11
12
13
/*   * *
* Get the directory size
* @param directory $directory
* @return integer
*/
 
function get_dir_size($directory) {
    $size = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
        $size += $file->getSize();
    }
    return $size;
}
/*	 * *
* Get the directory size
* @param directory $directory
* @return integer
*/

function get_dir_size($directory) {
    $size = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
        $size += $file->getSize();
    }
    return $size;
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
213 words
Last Post: Small Logo Programs, Interesting Output
Next Post: Return in Try-Finally for Python/Java/Delphi/C#

The Permanent URL is: Get Folder Size in PHP

One Response

  1. realmag777

Leave a Reply