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

PHP 文件列表展示:支援按類型排序的上傳文件管理頁面

     編輯:PHP 相關知識

功能概覽

  • 掃描指定上傳目錄下的所有文件
  • 顯示文件名、大小、修改時間
  • 支援按文件類型(擴展名)排序
  • 提供繼續上傳、返回首頁鏈接

完整代碼 index.php

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>上傳文件列表</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; max-width: 800px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background: #f4f4f4; }
        .actions { margin-top: 20px; }
        .actions a { margin-right: 15px; }
    </style>
</head>
<body>
<h2>上傳文件列表</h2>

<?php
define('UPLOAD_DIR', __DIR__ . '/../filehandle/uploadfile/');

$sort = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$files = [];

if (is_dir(UPLOAD_DIR)) {
    $handle = opendir(UPLOAD_DIR);
    while (($file = readdir($handle)) !== false) {
        if ($file === '.' || $file === '..') continue;
        $path = UPLOAD_DIR . $file;
        if (is_file($path)) {
            $files[] = [
                'name' => $file,
                'size' => filesize($path),
                'mtime' => filemtime($path),
                'ext' => strtolower(pathinfo($file, PATHINFO_EXTENSION))
            ];
        }
    }
    closedir($handle);
}

// 排序
usort($files, function($a, $b) use ($sort) {
    if ($sort === 'type') {
        $cmp = strcmp($a['ext'], $b['ext']);
        return $cmp !== 0 ? $cmp : strcmp($a['name'], $b['name']);
    }
    return strcmp($a['name'], $b['name']); // 默認按名稱
});
?>

<table>
    <thead>
        <tr>
            <th>文件名</th>
            <th>類型</th>
            <th>大小</th>
            <th>修改時間</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($files as $f): ?>
        <tr>
            <td><a href="" target="_blank"></a></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<div class="actions">
    <a href="?sort=name">按名稱排序</a>
    <a href="?sort=type">按類型排序</a>
    <a href="upfile.html">繼續上傳</a>
    <a href="index.php">返回首頁</a>
</div>

<?php
function formatSize(int $bytes): string {
    $units = ['B', 'KB', 'MB', 'GB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units)-1) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 2) . ' ' . $units[$i];
}
?>
</body>
</html>

關鍵點解析

  1. 目錄掃描:使用 opendir()/readdir() 遍歷,過濾 . 和 ..。
  2. 文件信息獲取:filesize()、filemtime()、pathinfo() 取擴展名。
  3. 靈活排序:usort() 配合匿名函數,根據 $_GET['sort'] 動態切換排序邏輯。
  4. 安全輸出:文件名輸出時使用 htmlspecialchars() 防 XSS。

擴展建議

  • 增加分頁功能,避免文件過多導致頁面過長。
  • 添加刪除、重命名、下載等操作按鈕(需配合 CSRF 保護)。
  • 對圖片文件顯示縮略圖預覽。
  • 記錄上傳者、上傳時間等元數據到數據庫,而非僅依賴文件系統。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved