-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfunction.dirsize.php
68 lines (58 loc) · 1.69 KB
/
function.dirsize.php
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
/**
* Calculate the size of a directory by iterating its contents
*
* @author Aidan Lister <[email protected]>
* @version 1.2.0
* @link http://aidanlister.com/repos/v/function.dirsize.php
* @param string $directory Path to directory
*/
function dirsize($path)
{
// Init
$size = 0;
// Trailing slash
if (substr($path, -1, 1) !== DIRECTORY_SEPARATOR) {
$path .= DIRECTORY_SEPARATOR;
}
// Sanity check
if (is_file($path)) {
return filesize($path);
} elseif (!is_dir($path)) {
return false;
}
// Iterate queue
$queue = array($path);
for ($i = 0, $j = count($queue); $i < $j; ++$i)
{
// Open directory
$parent = $i;
if (is_dir($queue[$i]) && $dir = @dir($queue[$i])) {
$subdirs = array();
while (false !== ($entry = $dir->read())) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Get list of directories or filesizes
$path = $queue[$i] . $entry;
if (is_dir($path)) {
$path .= DIRECTORY_SEPARATOR;
$subdirs[] = $path;
} elseif (is_file($path)) {
$size += filesize($path);
}
}
// Add subdirectories to start of queue
unset($queue[0]);
$queue = array_merge($subdirs, $queue);
// Recalculate stack size
$i = -1;
$j = count($queue);
// Clean up
$dir->close();
unset($dir);
}
}
return $size;
}