原版代碼
<?php
function dirtree($path = "./test") {
echo "<dl>";
$d = dir($path);
while (false !== ($v = $d->read())) {
if ($v == "." || $v == "..") continue;
$file = $d->path . "/" . $v;
echo "<dt>$v";
if (is_dir($file)) dirtree($file);
}
$d->close();
echo "</dl>";
}
dirtree();
?>
輸出結構範例
<dl>
<dt>file1.txt
<dt>subdir
<dl>
<dt>file2.txt
</dl>
<dt>file3.jpg
</dl>
改進版:支援陣列回傳、過濾、排序、深度限制
/**
* 遞迴掃描目錄,回傳結構化陣列
* @param string $path 起始路徑
* @param int $maxDepth 最大深度 (0=無限制)
* @param array $filter 允許的副檔名 ['jpg','png'] 或 null=全部
* @param bool $sort 是否排序
* @return array
*/
function scanDirectory($path, $maxDepth = 0, $filter = null, $sort = true) {
$path = rtrim($path, '/\\');
if (!is_dir($path)) return [];
$depth = 0;
$result = _scanRecursive($path, $depth, $maxDepth, $filter);
if ($sort) {
usort($result, function($a, $b) {
// 目錄優先、同類按名稱排序
if ($a['is_dir'] != $b['is_dir']) return $b['is_dir'] ? 1 : -1;
return strnatcasecmp($a['name'], $b['name']);
});
}
return $result;
}
function _scanRecursive($path, &$depth, $maxDepth, $filter) {
$items = [];
$handle = @opendir($path);
if (!$handle) return $items;
while (($entry = readdir($handle)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$fullPath = $path . '/' . $entry;
$isDir = is_dir($fullPath);
// 副檔名過濾
if (!$isDir && $filter !== null) {
$ext = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
if (!in_array($ext, $filter)) continue;
}
$item = [
'name' => $entry,
'path' => $fullPath,
'relative' => ltrim(str_replace($path, '', $fullPath), '/'),
'is_dir' => $isDir,
'size' => $isDir ? 0 : filesize($fullPath),
'mtime' => filemtime($fullPath),
'children' => []
];
// 遞迴子目錄
if ($isDir && ($maxDepth === 0 || $depth < $maxDepth)) {
$depth++;
$item['children'] = _scanRecursive($fullPath, $depth, $maxDepth, $filter);
$depth--;
}
$items[] = $item;
}
closedir($handle);
return $items;
}
// 使用範例
$tree = scanDirectory('./uploads', 3, ['jpg','png','gif']);
echo json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
SPL 迭代器現代寫法(推薦 PHP 5.3+)
function scanDirectorySPL($path, $maxDepth = 0, $filter = null) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
$iterator->setMaxDepth($maxDepth ?: -1);
$result = [];
foreach ($iterator as $file) {
if ($filter && $file->isFile()) {
$ext = strtolower($file->getExtension());
if (!in_array($ext, $filter)) continue;
}
$result[] = [
'name' => $file->getBasename(),
'path' => $file->getPathname(),
'relative' => $iterator->getSubPathName(),
'is_dir' => $file->isDir(),
'size' => $file->isFile() ? $file->getSize() : 0,
'mtime' => $file->getMTime(),
];
}
return $result;
}
輸出為 HTML 巢狀清單
function renderTreeHtml($tree, $level = 0) {
if (empty($tree)) return '';
$html = str_repeat(' ', $level) . "\n";
foreach ($tree as $item) {
$html .= str_repeat(' ', $level+1) . "- ";
$html .= $item['is_dir'] ? "{$item['name']}" : $item['name'];
if ($item['children']) $html .= "\n" . renderTreeHtml($item['children'], $level+2);
$html .= "
\n";
}
$html .= str_repeat(' ', $level) . "
\n";
return $html;
}
echo renderTreeHtml($tree);
效能與記憶體考量
- 大目錄避免一次載入所有結果 → 使用 Generator (yield) 逐個產出
- 避免在迴圈中重複呼叫
filesize()/filemtime() 等 stat 系統調用
- 生產環境快取掃描結果(Redis/檔案快取)
Generator 版本
function scanDirectoryGen($path, $maxDepth = 0) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
if ($maxDepth > 0) $iterator->setMaxDepth($maxDepth);
foreach ($iterator as $file) {
yield [
'name' => $file->getBasename(),
'path' => $file->getPathname(),
'is_dir' => $file->isDir(),
'size' => $file->isFile() ? $file->getSize() : 0,
];
}
}
// 使用:逐個處理,記憶體常數
foreach (scanDirectoryGen('./huge_dir') as $item) {
// 處理單項...
}