opendir($path):開啟目錄句柄。readdir($handle):逐個讀取項目(含 . ..)。closedir($handle):關閉句柄。filesize()、filetype()、filemtime():取得檔案屬性。<?php
$dir = __DIR__; // 當前腳本目錄
$dh = opendir($dir);
echo '<table border="1" cellpadding="6" style="border-collapse:collapse;">';
echo '<tr><th>檔名</th><th>大小</th><th>類型</th><th>修改時間</th></tr>';
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $file;
echo '<tr>';
echo '<td>' . htmlspecialchars($file) . '</td>';
echo '<td>' . (is_file($path) ? number_format(filesize($path)) . ' B' : '-') . '</td>';
echo '<td>' . filetype($path) . '</td>';
echo '<td>' . date('Y-m-d H:i:s', filemtime($path)) . '</td>';
echo '</tr>';
}
closedir($dh);
echo '</table>';
?>
$it = new DirectoryIterator(__DIR__);
echo '<table><tr><th>檔名</th><th>大小</th><th>類型</th><th>修改時間</th></tr>';
foreach ($it as $file) {
if ($file->isDot()) continue;
echo '<tr>';
echo '<td>' . htmlspecialchars($file->getFilename()) . '</td>';
echo '<td>' . ($file->isFile() ? $file->getSize() . ' B' : '-') . '</td>';
echo '<td>' . $file->getType() . '</td>';
echo '<td>' . $file->getMTime() . '</td>';
echo '</tr>';
}
echo '</table>'
$rdi = new RecursiveDirectoryIterator(__DIR__);
$it = new RecursiveIteratorIterator($rdi);
foreach ($it as $file) {
if ($file->isFile()) {
echo $file->getPathname() . ' (' . $file->getSize() . " B)\n";
}
}
傳統 opendir/readdir 適合簡單腳本,現代專案推薦 SPL 迭代器:物件導向、可鏈式過濾、支援遞迴、符合 PSR 風格。