PHP 5 引入 **SPL (Standard PHP Library)** 的 DirectoryIterator,提供物件導向、記憶體高效的目錄遍歷方式,取代傳統 opendir/readdir 組合。本文示範如何用它產生檔案下拉選單,並延伸至遞迴遍歷、過濾、排序等進階用法。
<?php
$dirPath = __DIR__ . '/uploads'; // 指定目錄
if (!is_dir($dirPath)) {
echo "目錄不存在
";
exit;
}
echo "\n";
function humanFilesize(int $bytes, int $decimals = 2): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f %s", $bytes / 1024 ** $factor, $units[$factor]);
}
?>
| 方法 | 說明 |
|---|---|
getFilename() | 檔名(含副檔名) |
getBasename($suffix) | 檔名(可移除副檔名) |
getPathname() | 完整路徑 |
getPath() | 目錄路徑 |
getSize() | 檔案大小(位元組) |
getMTime() | 最後修改時間(Unix 時間戳) |
getCTime() | 建立時間(Unix 時間戳) |
isFile() | 是否為一般檔案 |
isDir() | 是否為目錄 |
isDot() | 是否為 . 或 .. |
isLink() | 是否為符號連結 |
isReadable() / isWritable() | 權限檢查 |
getPerms() | 權限位元遮罩 |
getOwner() / getGroup() | 擁有者 UID/GID |
getType() | 類型:file, dir, link 等 |
openFile($mode) | 回傳 SplFileObject 進行檔案操作 |
RecursiveDirectoryIterator + RecursiveIteratorIterator + RegexIterator 組合拳:
<?php
$root = __DIR__ . '/storage';
// 遞迴迭代器
$rdi = new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS);
$rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST);
// 過濾:只要 .php、.html、.twig 檔案
$filter = new RegexIterator($rii, '/\.(php|html|twig)$/i');
// 排序:需先收集到陣列(迭代器無法直接排序)
$files = iterator_to_array($filter);
usort($files, fn($a, $b) => strcmp($a->getPathname(), $b->getPathname()));
// 輸出
echo "\n";
foreach ($files as $f) {
$rel = str_replace($root . DIRECTORY_SEPARATOR, '', $f->getPathname());
echo " - ", htmlspecialchars($rel), " (", humanFilesize($f->getSize()), ")
\n";
}
echo "
\n";
?>
SplFileInfo,不會一次將所有檔名載入記憶體(scandir() 會)。scandir() 可能耗盡記憶體,迭代器則穩定。FilterIterator、CallbackFilterIterator、LimitIterator 等,構建管線。RuntimeException,需 try-catch 或設定 FilesystemIterator::SKIP_DOTS 以外的旗標。FilesystemIterator::FOLLOW_SYMLINKS 謹慎開啟。若專案需支援多種儲存後端(本地、S3、FTP、Azure、Zip 等),建議採用 Flysystem:
<?php
use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;
$fs = new Filesystem(new LocalFilesystemAdapter(__DIR__ . '/uploads'));
$files = $fs->listContents('', true); // 遞迴列出
foreach ($files as $file) {
if ($file['type'] === 'file') {
echo $file['path'], ' ', $file['size'], ' bytes', "\n";
}
}
?>
DirectoryIterator 是 PHP 核心庫的珍寶,善用它能寫出更乾淨、高效、可維護的檔案系統代碼。