Algorithms, Blockchain and Cloud

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

    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:

/*	 * *
* 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) —

196 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 (AMP Version)

Exit mobile version