首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 目錄操作實戰:遞迴掃描、檔案計數與資料夾大小計算

     編輯:PHP 綜合知識

場景一:遞迴掃描並輸出目錄樹

function scanDir(string $path, int $depth = 0): void {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($iterator as $file) {
        $indent = str_repeat('  ', $iterator->getDepth());
        $name   = htmlspecialchars($file->getFilename());
        $full   = $file->getPathname();

        if ($file->isDir()) {
            echo "{$indent}{$name}/
"; } else { $size = $file->getSize(); echo "{$indent}{$name} ({$size} bytes)
"; } } } scanDir('/var/www/html/project');

優點: 使用 SPL 迭代器,自動處理遞迴、跳過 . ..、記憶體效率佳。

場景二:單層目錄列表(非遞迴)

function listFiles(string $dir): array {
    $files = [];
    if ($handle = opendir($dir)) {
        while (($entry = readdir($handle)) !== false) {
            if ($entry !== '.' && $entry !== '..' && $entry !== 'Thumbs.db') {
                $files[] = $entry;
            }
        }
        closedir($handle);
    }
    return $files;
}

場景三:計算資料夾總大小(含子目錄)

function getDirSize(string $path): int {
    $size = 0;
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($iterator as $file) {
        if ($file->isFile()) $size += $file->getSize();
    }
    return $size;
}

function formatBytes(int $bytes, int $precision = 2): string {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    return sprintf('%.*f %s', $precision, $bytes / (1024 ** $pow), $units[$pow]);
}

echo formatBytes(getDirSize('/var/www/html')); // 例:12.34 MB

效能與安全提醒

  • 大型目錄:遞迴掃描可能耗時、佔記憶體,建議搭配 set_time_limit() 或分批處理(Generator)。
  • 權限檢查:is_readable() 預先過濾不可讀目錄,避免例外中斷。
  • 符號連結:FilesystemIterator::FOLLOW_SYMLINKS 需謹慎啟用,防止循環掃描。
  • 快取結果:若頻繁查詢同目錄,可將大小寫入 Redis/檔案快取,設定 TTL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved