DirectoryIterator 實作 Iterator 介面,可直接 foreach 遍歷目錄,物件提供豐富檔案資訊方法。
<?php
echo "<select name='file'>\n";
foreach (new DirectoryIterator('c:\wamp\www') as $file) {
echo '<option>' . htmlspecialchars((string)$file) . "</option>\n";
}
echo '</select>';
?>
| 方法 | 回傳 | 說明 |
|---|---|---|
| getFilename() | string | 檔名 (不含路徑) |
| getPathname() | string | 完整路徑 |
| isFile() | bool | 是否為檔案 |
| isDir() | bool | 是否為目錄 |
| isDot() | bool | 是否為 . 或 .. |
| getSize() | int | 檔案大小 (位元組) |
| getMTime() | int | 修改時間 (Unix timestamp) |
| getPerms() | int | 權限位元遮罩 |
| __toString() | string | 同 getFilename() |
$files = [];
foreach (new DirectoryIterator('/var/www') as $file) {
if ($file->isFile() && !$file->isDot() && $file->getFilename()[0] !== '.') {
$files[] = $file;
}
}
usort($files, fn($a, $b) => $b->getSize() <=> $a->getSize()); // 大到小
echo "<select>";
foreach ($files as $f) {
echo "<option value='{$f->getPathname()}'>{$f->getFilename()} ({$f->getSize()} bytes)</option>";
}
echo "</select>";
RecursiveDirectoryIteratorGlobIterator (支援 *.php)FilesystemIterator (預設跳過 . 與 ..)DirectoryIterator 是 PHP 目錄掃描的標準物件導向介面,功能豐富且易用。