dir() 面向對象風格$dir = @dir('upload'); // @ 抑制目錄不存在警告
while (($file = $dir->read()) !== false) {
echo "文件名: $file
";
}
$dir->close();
返回 Directory 實例,提供 read()、rewind()、close()、path 屬性。
function treeDir($path) {
$dir = dir($path);
while (($file = $dir->read()) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $path . DIRECTORY_SEPARATOR . $file;
if (is_dir($full)) {
echo "目錄: $full
";
treeDir($full);
} else {
echo "文件: $full
";
}
}
$dir->close();
}
treeDir('./phpmyadmin');
opendir() + readdir() 過程風格
function listDir($path) {
if (!is_dir($path)) { echo "無效目錄"; return; }
$handle = opendir($path);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $path . DIRECTORY_SEPARATOR . $file;
if (is_dir($full)) {
echo "目錄: $full
";
listDir($full);
} else {
echo "文件: $full
";
}
}
closedir($handle);
}
listDir('./phpmyadmin');
// 遞歸遍歷,自動跳過 . 和 ..
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('./phpmyadmin', FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $fileInfo) {
echo $fileInfo->isDir() ? "目錄: " : "文件: ";
echo $fileInfo->getPathname() . "
";
}
// 只獲取 .php 文件
$phpFiles = new RegexIterator(
new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')),
'/\.php$/i'
);
foreach ($phpFiles as $f) echo $f->getPathname() . "
";
| 特性 | dir() | readdir() | SPL 迭代器 |
|---|---|---|---|
| 風格 | OO | 過程式 | OO/函數式 |
| 內存效率 | 逐個讀取 | 逐個讀取 | 逐個讀取(生成器特性) |
| 過濾/轉換 | 手動 | 手動 | RegexIterator, CallbackFilterIterator |
| 深度控制 | 手動遞歸 | 手動遞歸 | RecursiveIteratorIterator::setMaxDepth() |
| 文件信息 | 需額外 stat | 需額外 stat | SplFileInfo 內置 size/mtime/perms |
| 推薦指數 | ★★☆ | ★★☆ | ★★★★★ |
dir()/readdir() 仍可工作,但注意 === false 嚴格判斷防 0 值誤終止。exec('find ...') 或異步隊列分批處理,避免阻塞 Web 請求。