How to Determine Directory Size Using PHP
Calculating the size of a directory, including its subdirectories, can be an important task for managing file storage and performance. This article demonstrates how to achieve this in PHP using an optimized approach.
Existing Method
The provided PHP code snippet calculates the size of a directory as follows:
function foldersize($path) { $total_size = 0; $files = scandir($path); foreach($files as $t) { if (is_dir(rtrim($path, '/') . '/' . $t)) { if ($t<>"." && $t<>"..") { $size = foldersize(rtrim($path, '/') . '/' . $t); $total_size += $size; } } else { $size = filesize(rtrim($path, '/') . '/' . $t); $total_size += $size; } } return $total_size; }
Optimization
The original code exhibited performance issues due to unnecessary recursive function calls and redundant file exists checks. The optimized function below addresses these concerns:
function GetDirectorySize($path){ $bytestotal = 0; $path = realpath($path); if($path!==false && $path!='' && file_exists($path)){ foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){ $bytestotal += $object->getSize(); } } return $bytestotal; }
Key enhancements include:
Example Usage
Utilizing the optimized function:
$path = '/var/www/html/myproject'; $directorySize = GetDirectorySize($path); echo "Size of '$path': " . format_bytes($directorySize);
This code determines the size of the specified directory and displays the result in a human-readable format.
The above is the detailed content of How to Efficiently Calculate a Directory\'s Size in PHP?. For more information, please follow other related articles on the PHP Chinese website!