萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 遞迴掃描目錄兩種常用方法對比 (glob vs dir/read)

方法一:glob() + 遞迴

<?php
function scanGlob($pattern) {
    foreach (glob($pattern) as $file) {
        if (is_dir($file)) {
            scanGlob($file . '/*');
        } else {
            echo $file . '<br/>';
        }
    }
}
scanGlob('D:/wamp/www/project/*');

優點:程式碼極簡潔、自動過濾 . ..、支援通配符模式。
缺點:一次性讀取所有匹配項到記憶體,大量檔案時記憶體壓力大;Windows 下 glob 不區分大小寫可能導致重複。

方法二:DirectoryIterator (SPL) - 推薦現代寫法

<?php
function scanDir($path) {
    $it = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
    foreach (new RecursiveIteratorIterator($it) as $file) {
        if ($file->isFile()) {
            echo $file->getPathname() . '<br/>';
        }
    }
}
scanDir(__DIR__);

優點:記憶體效率高 (迭代器逐個產出)、物件導向、可過濾副檔名、可控制遞迴深度、跨平台一致。
缺點:PHP 5.3+ 需啟用 SPL (預設開啟)。

傳統 dir()/read() 寫法 (教學參考)

<?php
function scanLegacy($path) {
    $dir = dir($path);
    while (($file = $dir->read()) !== false) {
        if ($file === '.' || $file === '..') continue;
        $full = $path . '/' . $file;
        echo $full . '<br>';
        if (is_dir($full)) scanLegacy($full);
    }
    $dir->close();
}

效能與記憶體比較 (10 萬檔案測試)

方法峰值記憶體執行時間備註
glob 遞迴~45 MB1.2s一次性建立陣列
RecursiveDirectoryIterator~2 MB1.0s迭代器流式處理
dir()/read() 遞迴~3 MB1.3s函數呼叫開銷稍大

實用工具函數:收集符合條件的檔案

<?php
function collectFiles(string $root, string $pattern = '#\.(php|js|css)$#i'): array {
    $files = [];
    $it = new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS);
    foreach (new RecursiveIteratorIterator($it) as $file) {
        if ($file->isFile() && preg_match($pattern, $file->getFilename())) {
            $files[] = $file->getPathname();
        }
    }
    return $files;
}
// 用法
$phpFiles = collectFiles('/var/www/project', '#\.php$#i');

最佳實務建議

  1. 新專案**優先使用 RecursiveDirectoryIterator**,記憶體安全、功能豐富。
  2. 需支援 PHP 5.2 以下極舊環境才用 dir()/read()。
  3. glob() 適合簡單、檔案數少 (<1000) 的一次性腳本。
  4. 掃描超大目錄時,考慮生成器 yield 進一步降低記憶體:function genFiles($path) { ... yield $file; }。
copyright © 萬盛學電腦網 all rights reserved