函数实现
<?php
/**
* 递归计算目录大小(字节)
* @param string $dirPath 目录路径(建议以 DIRECTORY_SEPARATOR 结尾)
* @return int|false 总字节数,失败返回 -1
*/
function CalcDirectorySize($dirPath) {
// 规范化路径
$dirPath = rtrim($dirPath, '/\\') . DIRECTORY_SEPARATOR;
$size = 0;
$handle = @opendir($dirPath);
if (!$handle) return -1;
while (($file = readdir($handle)) !== false) {
// 跳过 . 和 ..
if ($file[0] === '.') continue;
$path = $dirPath . $file;
if (is_dir($path)) {
$subSize = CalcDirectorySize($path . DIRECTORY_SEPARATOR);
if ($subSize >= 0) $size += $subSize;
} elseif (is_file($path)) {
$size += filesize($path);
}
// 忽略链接、设备文件等
}
closedir($handle);
return $size;
}
// 可读性格式化
function humanFilesize($bytes, $decimals = 2) {
$units = array('B','KB','MB','GB','TB','PB');
$factor = floor((strlen((string)$bytes) - 1) / 3);
return sprintf("%.{$decimals}f %s", $bytes / (1024 ** $factor), $units[$factor]);
}
// 使用
$bytes = CalcDirectorySize('data/');
echo "目录大小: " . humanFilesize($bytes); // 例: 12.34 MB
关键点
- 使用
@opendir 抑制警告,手动判断返回值。
- 过滤
. .. 避免无限递归。
- 符号链接:
is_link() 可单独处理(统计目标大小/忽略/报错)。
- 权限不足目录会静默跳过,生产环境建议记录日志。
大目录性能优化
- 迭代器替代递归:
RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) 避免栈溢出。
- 并行统计:多进程分顶层子目录并行
du -sb 汇总。
- 缓存结果:文件变更不频繁时,Redis 缓存目录大小,定时/事件驱动更新。
- 系统命令:Linux 下
exec('du -sb ' . escapeshellarg($path)) 最快,但依赖环境。
SPL 迭代器版(推荐现代写法)
function dirSizeSPL($path) {
$ite = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
);
$size = 0;
foreach ($ite as $file) {
if ($file->isFile()) $size += $file->getSize();
}
return $size;
}