RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.38% (6.14%*) • Home Loan Fixed: 5.44% (6.26%*) • Fixed: 5.44% (6.26%*) • Variable: 5.38% (6.14%*) • Investment IO: 5.69% (6.52%*) • Investment PI: 5.49% (5.98%*)

Return the Size of an Entire Directory with PHP

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
function beliefmedia_directory_size($path) {
8
 
9
  $size = 0;
10
  if (substr($path, -1, 1) !== DIRECTORY_SEPARATOR) {
11
    $path .= DIRECTORY_SEPARATOR;
12
  }
13
 
14
  if (is_file($path)) {
15
    return filesize($path);
16
     } elseif (!is_dir($path)) {
17
    return false;
18
  }
19
 
20
  $queue = array($path);
21
  for ($i = 0, $j = count($queue); $i < $j; ++$i) {
22
    $parent = $i;
23
      if (is_dir($queue[$i]) && $dir = @dir($queue[$i])) {
24
        $subdirs = array();
25
          while (false !== ($entry = $dir->read())) {
26
            if ($entry == '.' || $entry == '..') {
27
              continue;
28
            }
29
 
30
            $path = $queue[$i] . $entry;
31
            if (is_dir($path)) {
32
              $path .= DIRECTORY_SEPARATOR;
33
              $subdirs[] = $path;
34
                } elseif (is_file($path)) {
35
              $size += filesize($path);
36
            }
37
          }
38
 
39
          unset($queue[0]);
40
          $queue = array_merge($subdirs, $queue);
41
          $i = -1;
42
          $j = count($queue);
43
 
44
          $dir->close();
45
          unset($dir);
46
    }
47
  }
48
 return $size;
49
}

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

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment