獲取目錄(含子目錄)總大小是常見需求。本文提供一個遞歸函數 dirSize(),遍歷目錄樹累加文件大小,並演示如何將位元組轉換為 KB/MB/GB 等人類可讀格式。
function dirSize($directory) {
$dirSize = 0;
if ($dirHandle = @opendir($directory)) {
while (($filename = readdir($dirHandle)) !== false) {
if ($filename === '.' || $filename === '..') continue;
$subPath = $directory . DIRECTORY_SEPARATOR . $filename;
if (is_dir($subPath)) {
$dirSize += dirSize($subPath); // 遞歸
} elseif (is_file($subPath)) {
$dirSize += filesize($subPath);
}
}
closedir($dirHandle);
}
return $dirSize;
}
// 使用
$size = dirSize("xym");
echo round($size / pow(1024, 1), 2) . " KB"; // 可改 pow(1024,2) 為 MB 等
@opendir 抑制警告,配合 readdir 遍歷。DIRECTORY_SEPARATOR 保證跨平台相容(Windows `\`、Linux `/`)。is_file() 確保只統計文件大小。pow(1024, n) 實現單位換算:1=KB, 2=MB, 3=GB...function formatSize($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$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];
}
echo formatSize(20667564); // 19.71 MB
RecursiveDirectoryIterator。filesize() 受限於 32 位系統的 2GB 限制,大文件需用 stat() 或 SplFileInfo。此函數簡潔高效,適合中小型目錄大小統計;大規模場景建議結合系統命令(du -sh)或專用掃描工具。