核心函數
opendir():開啟目錄控制代碼
readdir():讀取下一個項目
filetype():取得檔案類型(file/dir/link 等)
closedir():關閉目錄控制代碼
is_dir():檢查是否為目錄
完整程式碼範例
<?php
$dir = "./"; // 當前目錄
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>檔案名稱</th><th>類型</th></tr>";
while (($file = readdir($dh)) !== false) {
$fullPath = $dir . $file;
$type = filetype($fullPath);
echo "<tr>";
echo "<td>" . htmlspecialchars($file) . "</td>";
echo "<td>" . $type . "</td>";
echo "</tr>";
}
echo "</table>";
closedir($dh);
}
}
?>
執行結果範例
| 檔案名稱 | 類型 |
| . | dir |
| .. | dir |
| cms | dir |
| index.php | file |
| index.php.bak | file |
| mvc | dir |
| shop | dir |
| shop.rar | file |
| xampp | dir |
進階應用:遞迴掃描目錄樹
<?php
function scanDirTree($path, $level = 0) {
$indent = str_repeat(" ", $level);
$items = scandir($path);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $item;
$isDir = is_dir($fullPath);
echo $indent . ($isDir ? "📁 " : "📄 ") . $item . "<br>";
if ($isDir) {
scanDirTree($fullPath, $level + 1);
}
}
}
scanDirTree(".");
常用檔案類型常數
| 回傳值 | 意義 |
| file | 一般檔案 |
| dir | 目錄 |
| link | 符號連結 |
| fifo | 先進先出佇列 |
| block | 區塊裝置 |
| char | 字元裝置 |
| unknown | 未知類型 |