批量上傳是後台管理系統的高頻需求。本文提供一個完整可執行的範例,涵蓋:前端 jQuery 動態新增檔案欄位、後端 PHP 迴圈處理、檔案類型/大小驗證、隨機重命名防衝突、Session 防重複提交機制。
<?php
session_start();
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>PHP 批量上傳示範</title>
<style>
.container {max-width:600px;margin:50px auto;padding:20px;border:1px dashed #f90;background:#ffd3b6;font-family:Microsoft JhengHei;}
.file-row {margin:10px 0;}
.btn {padding:5px 15px;cursor:pointer;}
.msg {color:#f00;text-align:center;margin:10px 0;}
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head><body>
<div class="container">
<h1>PHP 多檔案批量上傳</h1>
<?php if (isset($_GET['up'])): // 處理上傳邏輯 ?>
<?php
// 防重複提交:Session Token 驗證
if (!isset($_SESSION['upload_token']) || $_SESSION['upload_token'] !== $_GET['token']) {
die('<div class="msg">請勿重複提交<br><a href="?">返回</a></div>');
}
unset($_SESSION['upload_token']); // 一次性 Token 失效
$maxSize = 2 * 1024 * 1024; // 2MB
$allowTypes = ['image/jpeg','image/pjpeg','image/png','image/x-png','image/gif'];
$saveDir = __DIR__ . '/uploads/';
if (!is_dir($saveDir)) mkdir($saveDir, 0755, true);
$count = intval($_POST['file_count'] ?? 0);
$success = 0;
for ($i = 0; $i < $count; $i++) {
if (!isset($_FILES['userfile']['tmp_name'][$i]) || $_FILES['userfile']['error'][$i] !== UPLOAD_ERR_OK) continue;
// 類型驗證
if (!in_array($_FILES['userfile']['type'][$i], $allowTypes)) {
echo "<div class='msg'>第 {$i+1} 檔案類型不允許</div>";
continue;
}
// 大小驗證
if ($_FILES['userfile']['size'][$i] > $maxSize) {
echo "<div class='msg'>第 {$i+1} 檔案超過 2MB</div>";
continue;
}
// 產生唯一檔名:時間戳 + 隨機數 + 原副檔名
$ext = pathinfo($_FILES['userfile']['name'][$i], PATHINFO_EXTENSION);
$newName = date('YmdHis') . '_' . mt_rand(1000,9999) . '.' . strtolower($ext);
$dest = $saveDir . $newName;
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $dest)) {
$success++;
echo "<div>✅ 第 {$i+1} 檔案上傳成功:{$newName} (" . round(filesize($dest)/1024,1) . " KB)</div>";
} else {
echo "<div class='msg'>第 {$i+1} 檔案移動失敗</div>";
}
}
echo "<div class='msg' style='color:green'>共成功上傳 {$success} 個檔案<br><a href='?'>繼續上傳</a></div>";
?>
<?php else: // 顯示上傳表單 ?>
<?php $_SESSION['upload_token'] = $token = bin2hex(random_bytes(16)); ?>
<form action="?up=1&token=<?=$token?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="file_count" id="file_count" value="1" />
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
<div class="file_row" id="file_1">
<input type="file" name="userfile[]" required />
</div>
<button type="button" id="add_file" class="btn">+ 新增檔案欄位</button>
<br><br>
<button type="submit" class="btn">開始上傳</button>
</form>
<?php endif; ?>
</div>
<script>
$(function(){
$('#add_file').click(function(){
var n = parseInt($('#file_count').val()) + 1;
$('#file_' + (n-1)).after('<div class="file_row" id="file_' + n + '"><input type="file" name="userfile[]" /> <button type="button" class="btn del_file">移除</button></div>');
$('#file_count').val(n);
});
$(document).on('click', '.del_file', function(){
$(this).parent('.file_row').remove();
$('#file_count').val($('.file_row').length);
});
});
</script>
</body></html>
name="userfile[]" 陣列命名,PHP 自動整理為 $_FILES['userfile'] 多檔結構file_count 記錄實際欄位數,避免遍歷空值| 層級 | 檢查項目 | 說明 |
|---|---|---|
| 客戶端 | HTML5 required、accept 屬性 | 基本攔截,可繞過 |
| 伺服器 | MIME 類型 $_FILES['type'] | 瀏覽器提供,可偽造 |
| 深度 | finfo_file() 檢測魔術位元組 | 真實檔案內容驗證,最可靠 |
建議補充:使用 finfo_open(FILEINFO_MIME_TYPE) 驗證真實 MIME:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$realMime = finfo_file($finfo, $_FILES['userfile']['tmp_name'][$i]);
if (!in_array($realMime, $allowTypes)) { /* 拒絕 */ }
表單載入時產生隨機 Token 存入 Session,提交時比對並銷毀。防止使用者重新整理或連點導致重複處理。
YmdHis_random.ext 格式極低機率衝突。高併發場景建議改用 uniqid('', true) 或 hash('sha256', $content)。
GD 或 Imagick 處理move_uploaded_file 替換為 S3/OSS SDK 上傳FormData + fetch/axios,後端回傳 JSONplupload 或 uppy 等前端庫