萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 掃描目錄圖片並分頁顯示:opendir/readdir 實作完整範例

專案常需展示上傳目錄下的圖片並支援分頁。本文提供純 PHP 實作:掃描目錄、過濾圖片副檔名、按修改時間倒序、分頁邏輯與導航生成,無框架依賴,即刻可用。

完整程式碼

<div style="width: 90%; margin: 10px auto; border: 1px solid #ccc; text-align: center">
<?php
$page   = isset($_GET['page']) ? (int)$_GET['page'] : 0;  // 從 0 開始
$perPage = 10;                                           // 每頁圖片數
$path   = "uploads";                                     // 圖片目錄

$handle = opendir($path);
$files = [];

while (false !== ($file = readdir($handle))) {
    // 跳過 . .. 目錄
    if ($file === '.' || $file === '..') continue;
    
    // 過濾圖片副檔名 (不分大小寫)
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if (!in_array($ext, ['gif', 'jpg', 'jpeg', 'png', 'webp'])) continue;
    
    // 確保是檔案非目錄
    $fullPath = $path . DIRECTORY_SEPARATOR . $file;
    if (!is_file($fullPath)) continue;
    
    // 取得修改時間用於排序
    $files[$file] = filemtime($fullPath);
}
closedir($handle);

// 按修改時間倒序 (最新優先)
arsort($files);
$files = array_keys($files);

$totalFiles = count($files);
$totalPages = (int)ceil($totalFiles / $perPage) - 1;  // 0-based

// 分頁切片
$offset = $page * $perPage;
$pageFiles = array_slice($files, $offset, $perPage);

// 輸出圖片
foreach ($pageFiles as $file) {
    $fullPath = $path . '/' . $file;
    echo '<div style="display:inline-block; margin:10px; text-align:center;">';
    echo '<div>' . htmlspecialchars($file) . '</div>';
    echo '<img src="' . htmlspecialchars($fullPath) . '" style="max-width:200px; max-height:200px;" />';
    echo '</div>';
}

// 分頁導航
echo '<div style="padding:10px;">';
if ($page > 0) {
    echo '<a href="?page=' . ($page - 1) . '">上一頁</a> ';
}
for ($i = 0; $i <= $totalPages; $i++) {
    $style = ($i === $page) ? 'font-weight:bold; color:red;' : '';
    echo '<a href="?page=' . $i . '" style="margin:0 5px;' . $style . '">' . ($i + 1) . '</a> ';
}
if ($page < $totalPages) {
    echo '<a href="?page=' . ($page + 1) . '">下一頁</a> ';
}
echo '</div>';
?>
</div>

核心邏輯解析

  1. 掃描目錄:opendir() + readdir() + closedir()
  2. 過濾條件:副檔名白名單 + is_file() 排除子目錄
  3. 排序依據:filemtime() 取修改時間,arsort() 保持鍵值關聯倒序
  4. 分頁計算:0-based 頁碼,array_slice() 切片
  5. 導航生成:動態計算上/下頁、頁碼連結、當前頁高亮

效能優化建議

進階:SPL DirectoryIterator 寫法 (PHP 5.3+)

<?php
$dir = new DirectoryIterator($path);
$files = [];

foreach ($dir as $fileinfo) {
    if ($fileinfo->isDot() || !$fileinfo->isFile()) continue;
    $ext = strtolower($fileinfo->getExtension());
    if (!in_array($ext, ['gif','jpg','jpeg','png','webp'])) continue;
    $files[$fileinfo->getFilename()] = $fileinfo->getMTime();
}

arsort($files);
// 後續分頁邏輯相同
?>

安全性加固

<?php
// 防止目錄遍歷
$requestedPath = realpath($path . '/' . $file);
$allowedRoot = realpath($path);
if ($requestedPath === false || strpos($requestedPath, $allowedRoot) !== 0) {
    die('非法路徑');
}

// 輸出時編碼
echo '<img src="' . htmlspecialchars($fullPath) . '" />';
?>

此實作涵蓋目錄掃描、圖片過濾、時間排序、分頁顯示、導航生成全流程,適合快速構建圖片庫、相簿、上傳管理等功能模組。

copyright © 萬盛學電腦網 all rights reserved
問題解決方案
大目錄掃描緩慢快取檔案列表 (Redis/檔案快取),定期/事件驅動更新
重複統計 filemtime掃描時一次性收集,避免重複 stat 系統調用
輸出大量圖片阻塞前端懶加載 (loading="lazy")、分頁 API 回傳 JSON
目錄遍歷攻擊實際專案用 realpath() 驗證路徑在允許根目錄內