專案常需掃描目錄樹(如建立檔案索引、批次處理、清理臨時檔)。本文提供健壯、可擴充的遞迴遍歷函式,支援符號連結保護、權限錯誤處理、記憶體效率優化與迭代器模式替代方案。
<?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+,自訂迭代邏輯 |
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') {
// 處理單一檔案
}
}
根據專案規模與環境限制選擇適當實作:小腳本用基礎遞迴,長期服務用迭代器或 Generator,確保穩定高效。