多檔案上傳的關鍵在於前端使用陣列命名 name="imgfile[]",後端遍歷 $_FILES['imgfile'] 的各屬性陣列(name、type、tmp_name、size、error)逐一處理。本文展示支援最多 5 張圖片、格式白名單驗證、重複檢查、結果統計的完整範例。
<?php
$imgDir = '../upload/'; // 確保目錄存在且可寫
$maxFiles = 5;
$allowedMimes = [
'image/jpeg', 'image/pjpeg', // JPG
'image/gif',
'image/png', 'image/x-png',
'image/bmp'
];
$uploaded = 0;
$failed = 0;
$results = [];
for ($i = 0; $i < $maxFiles; $i++) {
// 檢查是否有檔案
if (empty($_FILES['imgfile']['name'][$i])) continue;
$name = $_FILES['imgfile']['name'][$i];
$type = $_FILES['imgfile']['type'][$i];
$size = $_FILES['imgfile']['size'][$i];
$tmp = $_FILES['imgfile']['tmp_name'][$i];
$error = $_FILES['imgfile']['error'][$i];
// 錯誤碼處理
if ($error !== UPLOAD_ERR_OK) {
$results[$i] = ["name"=>$name, "size"=>$size, "type"=>$type, "status"=>"錯誤碼: $error"];
$failed++;
continue;
}
// MIME 型別驗證
if (!in_array($type, $allowedMimes)) {
$results[$i] = ["name"=>$name, "size"=>$size, "type"=>$type, "status"=>"<font color=red>格式不允許</font>"];
$failed++;
continue;
}
// 重複檢查
$targetPath = $imgDir . $name;
if (file_exists($targetPath)) {
$results[$i] = ["name"=>$name, "size"=>$size, "type"=>$type, "status"=>"<font color=red>檔案已存在</font>"];
$failed++;
continue;
}
// 移動檔案
if (move_uploaded_file($tmp, $targetPath)) {
$results[$i] = ["name"=>$name, "size"=>round($size/1024,2).'K', "type"=>$type, "status"=>"成功"];
$uploaded++;
} else {
$results[$i] = ["name"=>$name, "size"=>$size, "type"=>$type, "status"=>"<font color=red>移動失敗</font>"];
$failed++;
}
}
// 無任何檔案
if (empty($results)) {
die('請至少選擇一張圖片');
}
// 輸出結果表格
echo "<table border=1 cellpadding=4>";
echo "<tr><th>檔名</th><th>大小</th><th>類型</th><th>結果</th></tr>";
foreach ($results as $row) {
echo "<tr><td>{$row['name']}</td><td>{$row['size']}</td><td>{$row['type']}</td><td>{$row['status']}</td></tr>";
}
echo "<tr><td colspan=4>共 " . ($uploaded+$failed) . " 筆,成功: $uploaded,失敗: <font color=red>$failed</font></td></tr>";
echo "</table>";
echo "[<a href='?action=upload'>繼續上傳</a>] [<a href='image.php'>瀏覽圖片</a>]";
?>
finfo_file() 或 getimagesize() 驗證真實檔案內容uniqid() . '_' . mt_rand() . '.' . $ext 避免中文檔名、覆蓋、路徑遍歷chmod 755、禁止執行權限、置於 Webroot 外.htaccess 加入 SetHandler default-handler、Options -ExecCGIlocation ~ \.php$ { deny all; } 於上傳目錄open_basedir 限制腳本存取範圍批次上傳是圖庫、商品管理、相簿系統的基礎功能,建立安全、可擴充的上傳管線至關重要。