計算目錄總大小是常見運維需求。本文提供生產級遞歸實現,並針對深層目錄、海量文件、權限異常三大痛點給出優化方案。
<?php
function dirSize(string $dir): int {
$size = 0;
$dh = @opendir($dir);
if (!$dh) return 0; // 權限不足或非目錄
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
$size += dirSize($path); // 遞歸
} elseif (is_file($path)) {
$size += filesize($path);
}
// 忽略鏈接、設備文件等特殊類型
}
closedir($dh);
return $size;
}
// 使用
$bytes = dirSize('/var/www/html');
echo "大小: " . formatBytes($bytes); // 自定義格式化函數
function formatBytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
<?php
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
function dirSizeIterative(string $dir): int {
$size = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isFile()) {
$size += $fileInfo->getSize();
}
}
return $size;
}
優勢:無遞歸深度限制、內存效率高、可中斷、支援並行處理。
<?php
function dirSizeSystem(string $dir): ?int {
// Linux/Unix: du -sb (字節級汇總,極快)
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
$cmd = sprintf('du -sb %s 2>/dev/null', escapeshellarg($dir));
$output = shell_exec($cmd);
if ($output !== null) {
return (int)explode("\t", $output)[0];
}
}
// Windows: dir /s /-c (較慢,備選)
$cmd = sprintf('dir /s /-c %s 2>nul', escapeshellarg($dir));
$output = shell_exec($cmd);
if ($output !== null && preg_match('/\s+(\d+)\s+bytes?\s*$/m', $output, $m)) {
return (int)$m[1];
}
return null; // 降級到 PHP 實現
}
性能對比 (10萬文件、5GB 目錄):
| 方法 | 耗時 | CPU | 適用場景 |
|---|---|---|---|
| PHP 遞歸 | 45 秒 | 高 | 小目錄、跨平台、無執行權限 |
| PHP 迭代器 | 38 秒 | 中 | 中等目錄、需 PHP 邏輯控制 |
系統 du | 1.2 秒 | 低 | 大目錄、Linux 生產環境、有 shell 執行權限 |
<?php
class DirectorySizeCache {
private string $cacheFile;
private int $ttl;
public function __construct(string $cacheDir, int $ttl = 3600) {
$this->cacheFile = $cacheDir . '/dirsize_' . md5($dir) . '.cache';
$this->ttl = $ttl;
}
public function getSize(string $dir): int {
// 檢查緩存有效性
if (file_exists($this->cacheFile) && (time() - filemtime($this->cacheFile)) < $this->ttl) {
return (int)file_get_contents($this->cacheFile);
}
// 計算並緩存
$size = dirSizeSystem($dir) ?? dirSizeIterative($dir);
file_put_contents($this->cacheFile, (string)$size, LOCK_EX);
return $size;
}
public function invalidate(string $dir): void {
@unlink($this->cacheFile);
}
}
<?php
function dirSizeRobust(string $dir, array &$errors = []): int {
$size = 0;
if (!is_readable($dir)) {
$errors[] = "不可讀目錄: $dir";
return 0;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS),
RecursiveIteratorIterator::CATCH_GET_CHILD // 關鍵:捕獲子迭代器異常
);
foreach ($iterator as $path => $fileInfo) {
try {
if ($fileInfo->isFile()) {
$size += $fileInfo->getSize();
} elseif ($fileInfo->isLink()) {
// 可選:統計鏈接目標大小或忽略
// $size += $fileInfo->getSize();
}
} catch (Throwable $e) {
$errors[] = "讀取失敗 [$path]: " . $e->getMessage();
// 繼續處理其他文件
}
}
return $size;
}
| 場景 | 推薦方案 | 關鍵點 |
|---|---|---|
| 臨時腳本/小目錄 | 基礎遞歸 | 代碼簡單、零依賴 |
| 常規業務/中等目錄 | RecursiveIteratorIterator | 無棧溢出、可擴展過濾邏輯 |
| 大目錄/高頻/生產環境 | 系統 du + 緩存 | 秒級響應、低資源佔用 |
| 跨平台/無 shell 權限 | 迭代器 + 緩存 | 純 PHP、可移植 |
核心原則:能用系統命令就不用 PHP 遍歷,能用緩存就不重複計算,必須處理權限異常與符號鏈接。