Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Return the Size of an Entire Directory with PHP

On a member-based site we operate we put a limit on the size of a directory before additional credit is required. The following function will recursively look through an entire directory and return a filesize. While the value returned is in bytes, you can alter it into a human readable string by using the first function from this article ("Return a Readable Filesize with PHP").

The PHP Function

1
<?php 
2
/*
3
    Return the Size of an Entire Directory with PHP
4
    http://www.beliefmedia.com/return-size-directory-php
5
*/
6
 
7
 
8
function beliefmedia_directory_size($path) {
9
 
10
  $size = 0;
11
  if (substr($path, -1, 1) !== DIRECTORY_SEPARATOR) {
12
    $path .= DIRECTORY_SEPARATOR;
13
  }
14
 
15
  if (is_file($path)) {
16
    return filesize($path);
17
     } elseif (!is_dir($path)) {
18
    return false;
19
  }
20
 
21
  $queue = array($path);
22
  for ($i = 0, $j = count($queue); $i < $j; ++$i) {
23
    $parent = $i;
24
      if (is_dir($queue[$i]) && $dir = @dir($queue[$i])) {
25
        $subdirs = array();
26
          while (false !== ($entry = $dir->read())) {
27
            if ($entry == '.' || $entry == '..') {
28
              continue;
29
            }
30
 
31
            $path = $queue[$i] . $entry;
32
            if (is_dir($path)) {
33
              $path .= DIRECTORY_SEPARATOR;
34
              $subdirs[] = $path;
35
                } elseif (is_file($path)) {
36
              $size += filesize($path);
37
            }
38
          }
39
 
40
          unset($queue[0]);
41
          $queue = array_merge($subdirs, $queue);
42
          $i = -1;
43
          $j = count($queue);
44
 
45
          $dir->close();
46
          unset($dir);
47
    }
48
  }
49
 return $size;
50
}

Usage is as follows:

1
/* Usage */
2
echo beliefmedia_directory_size('/home/user/public_html/dir');

Download

Title: Return the Size of an Entire Directory with PHP
Description: Return the Size of an Entire Directory with PHP.
  Download • Version 0.2, 709.0B, zip, Category: PHP Code & Snippets

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433