<?php
function listDir($dir) {
if (!file_exists($dir) || !is_dir($dir)) return '';
$it = new DirectoryIterator($dir);
$list = ['dirNum'=>0, 'fileNum'=>0, 'lists'=>[]];
while ($it->valid()) {
if (!$it->isDot()) {
$list['lists'][$it->key()]['name'] = $it->getFilename();
if ($it->isDir()) {
$list['dirNum']++;
$list['lists'][$it->key()]['isDir'] = 1;
} else {
$list['fileNum']++;
$list['lists'][$it->key()]['isDir'] = '';
}
}
$it->next();
}
return $list;
}
?>
| 方法 | 說明 |
|---|---|
| __construct($path) | 構建目錄迭代器 |
| current() | 返回當前 SplFileInfo 對象 |
| getFilename() | 返回文件名 |
| getPathname() | 返回完整路徑 |
| isDir() / isFile() / isLink() | 判斷類型 |
| isDot() | 是否為 . 或 .. |
| getSize() / getMTime() / getATime() / getCTime() | 大小、修改/訪問/變更時間 |
| getPerms() / getOwner() / getGroup() / getInode() | 權限、擁有者、組、inode |
| key() / next() / rewind() / valid() | 迭代器標準接口 |
繼承 DirectoryIterator,新增 hasChildren()、getChildren()。配合 RecursiveIteratorIterator 可平鋪輸出所有層級文件。
| 方法 | 說明 |
|---|---|
| getDepth() | 當前遞歸深度 |
| getSubIterator() | 當前活動子迭代器 |
| current() / key() / next() / rewind() / valid() | 遍歷控制 |
SPL 提供了強大、標準化的目錄操作接口,推薦替代傳統 opendir/readdir。