In web development, there are situations where you need to determine how much disk space a specific directory (and its subdirectories) is using—for example, for storage limits, usage reporting, or monitoring logs. PHP provides several built-in functions that can help calculate directory disk usage effectively.
The disk_total_space() function returns the total space of the entire disk, not just the directory. It’s useful when you want to know the full capacity of the disk where the directory resides.
$directory = "/var/log";
$total_space = disk_total_space($directory);
echo "Total disk capacity: $total_space bytes";
You can iterate through the directory using opendir() and use filesize() to accumulate the size of each file. This gives a more accurate measurement of actual disk usage for that directory.
$directory = "/var/log";
$total_size = 0;
if ($dh = opendir($directory)) {
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != "..") {
$total_size += filesize($directory . "/" . $file);
}
}
closedir($dh);
}
echo "Total disk usage: $total_size bytes";
To recursively scan a directory and its subdirectories, use RecursiveDirectoryIterator with RecursiveIteratorIterator. This method is ideal for deep directory structures.
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use SplFileInfo;
$directory = "/var/log";
$total_size = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$total_size += $file->getSize();
}
}
echo "Total disk usage: $total_size bytes";
scandir() returns the file list in a directory. Combined with array_map() and array_sum(), this approach provides a concise way to calculate size, though it doesn’t work recursively.
$directory = "/var/log";
$files = scandir($directory);
$total_size = array_sum(array_map("filesize", array_filter(
array_map(function($file) use ($directory) {
return $directory . '/' . $file;
}, $files),
function($file) {
return is_file($file);
}
)));
echo "Total disk usage: $total_size bytes";
PHP provides multiple approaches to calculate the disk size used by a directory. Choose the method that best fits your application’s needs. Efficient implementation and selecting the right functions can result in accurate and fast disk usage reporting.