萬盛學電腦網

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

PHP 遞迴遍歷目錄取得所有檔案與子目錄完整實作

專案常需掃描目錄樹(如建立檔案索引、批次處理、清理臨時檔)。本文提供健壯、可擴充的遞迴遍歷函式,支援符號連結保護、權限錯誤處理、記憶體效率優化與迭代器模式替代方案。

基礎遞迴版本(適合中小型目錄)

<?php
/**
 * 遞迴掃描目錄,回傳結構化陣列
 * @param string $dir 絕對路徑
 * @return array ['dirs' => [...], 'files' => [...]]
 */
function scanDirectoryRecursive($dir) {
    $dir = rtrim(realpath($dir), DIRECTORY_SEPARATOR);
    if ($dir === false || !is_dir($dir)) {
        throw new InvalidArgumentException("無效目錄: $dir");
    }

    $result = ['dirs' => [], 'files' => []];
    $handle = @opendir($dir);
    if (!$handle) {
        throw new RuntimeException("無法開啟目錄: $dir (權限不足?)");
    }

    while (($entry = readdir($handle)) !== false) {
        if ($entry === '.' || $entry === '..') continue;

        $path = $dir . DIRECTORY_SEPARATOR . $entry;

        // 避開符號連結導致無限遞迴
        if (is_link($path)) continue;

        if (is_dir($path)) {
            $result['dirs'][] = $path;
            // 遞迴合併
            $sub = scanDirectoryRecursive($path);
            $result['dirs'] = array_merge($result['dirs'], $sub['dirs']);
            $result['files'] = array_merge($result['files'], $sub['files']);
        } else {
            $result['files'][] = $path;
        }
    }
    closedir($handle);
    return $result;
}

// 使用
$tree = scanDirectoryRecursive('/var/www/project');
echo "目錄數: " . count($tree['dirs']) . "\n";
echo "檔案數: " . count($tree['files']) . "\n";
// print_r($tree);

生產級增強版(錯誤處理 + 過濾 + 迭代器)

<?php
class DirectoryScanner implements IteratorAggregate {
    private $root;
    private $filters = [];

    public function __construct(string $root) {
        $this->root = realpath($root);
        if (!$this->root) throw new InvalidArgumentException("Root not found: $root");
    }

    public function addFilter(callable $fn) { $this->filters[] = $fn; return $this; }
    public function skipHidden() { return $this->addFilter(fn($p) => basename($p)[0] !== '.'); }
    public function skipSymlinks() { return $this->addFilter(fn($p) => !is_link($p)); }
    public function onlyExtensions(array $exts) { 
        $exts = array_map('strtolower', $exts);
        return $this->addFilter(fn($p) => is_dir($p) || in_array(strtolower(pathinfo($p, PATHINFO_EXTENSION)), $exts));
    }

    public function getIterator(): Traversable {
        return new RecursiveCallbackFilterIterator(
            new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($this->root, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ),
            function ($current, $key, $iterator) {
                foreach ($this->filters as $fn) {
                    if (!$fn($current->getPathname())) return false;
                }
                return true;
            }
        );
    }

    public function getAllFiles(): array {
        return array_filter(iterator_to_array($this->getIterator()), 'is_file');
    }
    public function getAllDirs(): array {
        return array_filter(iterator_to_array($this->getIterator()), 'is_dir');
    }
}

// 使用:掃描專案所有 PHP 檔,跳過隱藏檔與符號連結
$scanner = (new DirectoryScanner('/var/www/project'))
    ->skipHidden()
    ->skipSymlinks()
    ->onlyExtensions(['php', 'phtml']);

foreach ($scanner->getAllFiles() as $file) {
    echo $file . "\n";
}

效能與記憶體考量

方法記憶體速度適用場景
遞迴函式回傳大陣列高(全樹載入記憶體)快小型目錄、一次性腳本
RecursiveIteratorIterator低(逐個產出)中大型目錄、長時間運行、記憶體受限
Generator (yield)極低中PHP 5.5+,自訂迭代邏輯

Generator 版本(PHP 5.5+,記憶體最省)

function scanDirGenerator($dir) {
    $dir = realpath($dir);
    $stack = [$dir];
    while ($stack) {
        $currentDir = array_pop($stack);
        $handle = @opendir($currentDir);
        if (!$handle) continue;
        while (($entry = readdir($handle)) !== false) {
            if ($entry === '.' || $entry === '..') continue;
            $path = $currentDir . DIRECTORY_SEPARATOR . $entry;
            if (is_link($path)) continue;
            if (is_dir($path)) {
                $stack[] = $path;
                yield $path; // 目錄
            } else {
                yield $path; // 檔案
            }
        }
        closedir($handle);
    }
}

// 使用:逐個處理,不佔記憶體
foreach (scanDirGenerator('/var/www/project') as $path) {
    if (is_file($path) && pathinfo($path, PATHINFO_EXTENSION) === 'php') {
        // 處理單一檔案
    }
}

權限錯誤處理最佳實務

  • 使用 `@opendir` 抑制警告,檢查回傳值 `false` 後記錄日誌並跳過。
  • 生產環境建議以獨立使用者身分運行掃描腳本,僅賦予必要讀取權限。
  • 遭遇 `Permission denied` 時記錄路徑並繼續,而非中斷整個掃描。

根據專案規模與環境限制選擇適當實作:小腳本用基礎遞迴,長期服務用迭代器或 Generator,確保穩定高效。

copyright © 萬盛學電腦網 all rights reserved