功能概覽
- 掃描指定上傳目錄下的所有文件
- 顯示文件名、大小、修改時間
- 支援按文件類型(擴展名)排序
- 提供繼續上傳、返回首頁鏈接
完整代碼 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="= UPLOAD_DIR . $f['name'] ?>" target="_blank">= htmlspecialchars($f['name']) ?></a></td>
<td>= strtoupper($f['ext']) ?: '未知' ?></td>
<td>= formatSize($f['size']) ?></td>
<td>= date('Y-m-d H:i:s', $f['mtime']) ?></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>
關鍵點解析
- 目錄掃描:使用
opendir()/readdir() 遍歷,過濾 . 和 ..。
- 文件信息獲取:
filesize()、filemtime()、pathinfo() 取擴展名。
- 靈活排序:
usort() 配合匿名函數,根據 $_GET['sort'] 動態切換排序邏輯。
- 安全輸出:文件名輸出時使用
htmlspecialchars() 防 XSS。
擴展建議
- 增加分頁功能,避免文件過多導致頁面過長。
- 添加刪除、重命名、下載等操作按鈕(需配合 CSRF 保護)。
- 對圖片文件顯示縮略圖預覽。
- 記錄上傳者、上傳時間等元數據到數據庫,而非僅依賴文件系統。