遞歸掃描目錄下所有檔案(忽略 . 與 ..),累加檔案大小,遇到子目錄則遞歸進入。回傳總位元組數,若目錄無法開啟則回傳 -1。
<?php
/**
* 遞歸計算目錄大小
* @param string $dirPath 目錄路徑(建議以 DIRECTORY_SEPARATOR 結尾)
* @return int 總位元組數,失敗回傳 -1
*/
function calcDirectorySize($dirPath) {
$size = 0;
$dh = @opendir($dirPath);
if (!$dh) return -1;
while (($file = readdir($dh)) !== false) {
if ($file[0] === '.') continue; // 跳過 . 與 ..
$full = $dirPath . $file;
if (is_dir($full)) {
$sub = calcDirectorySize($full . DIRECTORY_SEPARATOR);
if ($sub >= 0) $size += $sub;
} else {
$size += filesize($full);
}
}
closedir($dh);
return $size;
}
// 使用範例
$bytes = calcDirectorySize('data/');
echo "目錄大小:$bytes 位元組 (" . round($bytes/1024/1024,2) . " MB)";
?>
RecursiveDirectoryIterator + RecursiveIteratorIterator 迭代器模式。is_link() 判斷與 readlink() 處理。formatBytes())。<?php
function calcDirSizeIterator($path) {
$total = 0;
$ite = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));
foreach ($ite as $file) {
if ($file->isFile()) $total += $file->getSize();
}
return $total;
}
?>