首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 簡易目錄瀏覽器:opendir/readdir 實作檔案列表呈現

     編輯:PHP 綜合知識

核心函數

  • 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>';
?>

進階:SPL DirectoryIterator(物件導向、更強大)

$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>'

遞迴掃描:RecursiveDirectoryIterator

$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 風格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved