遞歸思路
- 打開目錄句柄
opendir()。
- 循環讀取
readdir(),跳過 . 和 ..。
- 若為子目錄 → 遞歸調用自身累加;若為文件 →
filesize() 累加。
- 關閉句柄,返回總位元組數。
完整函數
function dirsize($dir) {
$dh = @opendir($dir);
if (!$dh) return 0;
$size = 0;
while (($file = @readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
$size += dirsize($path);
} elseif (is_file($path)) {
$size += filesize($path);
}
}
@closedir($dh);
return $size;
}
使用範例:輸出 MB
$path = '/var/www/html';
$bytes = dirsize($path);
$mb = round($bytes / 1024 / 1024, 2);
echo "目錄大小:{$mb} MB";
效能優化建議
- 大量文件目錄遞歸深度可能導致堆疊溢出,可改用
RecursiveDirectoryIterator (SPL) 非遞歸遍歷。
- 頻繁查詢同一目錄時,考慮緩存結果或使用
du -sh 系統命令(需權限)。
- Windows 下
filesize() 對 >2GB 文件不準確,建議用 COM 組件或 stat 替代。