需要遞迴統計目錄下所有檔案大小總和時,RecursiveDirectoryIterator 搭配 RecursiveIteratorIterator 是最高效的原生做法。
<?php
$dir = new RecursiveDirectoryIterator('C:/wamp'); // Windows 路徑建議用正斜線
$totalSize = 0;
foreach (new RecursiveIteratorIterator($dir) as $file) {
if ($file->isFile()) {
$totalSize += $file->getSize();
}
}
echo "總大小: $totalSize 位元組";
echo "<br>總大小: " . human_readable_size($totalSize);
/**
* 將位元組轉為人類可讀格式
*/
function human_readable_size($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
?>
RecursiveDirectoryIterator 可遞迴遍歷子目錄。RecursiveIteratorIterator 將遞迴迭代器扁平化,方便 foreach 直接處理每個檔案物件。$file->isFile() 判斷,避免將目錄本身大小計入。/,跨平台相容性較佳。可進一步擴充為函式,支援排除特定子目錄、只統計特定副檔名、顯示各檔案大小明細等功能。