name=\"file[]\" 陣列語法<!DOCTYPE html>
<html>
<head>
<meta charset=\"utf-8\">
<title>多檔案上傳</title>
</head>
<body>
<form action=\"uploads.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"file[]\"><br>
<input type=\"file\" name=\"file[]\"><br>
<input type=\"file\" name=\"file[]\"><br>
<input type=\"submit\" value=\"上傳檔案\">
</form>
</body>
</html>
$_FILES 陣列結構解析多檔案上傳時,$_FILES['file'] 結構為:
Array
(
[name] => Array ( [0] => 'a.jpg', [1] => 'b.png', [2] => 'c.pdf' )
[type] => Array ( [0] => 'image/jpeg', [1] => 'image/png', [2] => 'application/pdf' )
[tmp_name] => Array ( [0] => '/tmp/phpX123', [1] => '/tmp/phpY456', [2] => '/tmp/phpZ789' )
[error] => Array ( [0] => 0, [1] => 0, [2] => 0 )
[size] => Array ( [0] => 12345, [1] => 67890, [2] => 24680 )
)
uploads.php<?php
header('Content-Type: text/html; charset=utf-8');
$uploadDir = __DIR__ . '/uploads/files/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$count = count($_FILES['file']['name']);
$success = 0;
$errors = [];
for ($i = 0; $i < $count; $i++) {
// 檢查上傳錯誤代碼
if ($_FILES['file']['error'][$i] !== UPLOAD_ERR_OK) {
$errors[] = "檔案 {$_FILES['file']['name'][$i]} 上傳失敗,錯誤代碼:{$_FILES['file']['error'][$i]}";
continue;
}
$tmpName = $_FILES['file']['tmp_name'][$i];
$origName = $_FILES['file']['name'][$i];
// 安全性:驗證副檔名與 MIME 類型
$ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
if (!in_array($ext, $allowedExt)) {
$errors[] = "檔案 $origName 副檔名不允許($ext)";
continue;
}
// 產生唯一檔名:時間戳_隨機數.副檔名
$newName = time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
$destPath = $uploadDir . $newName;
// 移動上傳檔案
if (move_uploaded_file($tmpName, $destPath)) {
$success++;
} else {
$errors[] = "檔案 $origName 移動失敗";
}
}
// 輸出結果
if ($success) {
echo "";
}
if ($errors) {
echo "";
}
?>
error 代碼:UPLOAD_ERR_OK (0) 才處理。.php、.exe 等可執行檔。finfo_file() 檢測真實類型,防偽裝副檔名。$_FILES['file']['size'][$i] > $maxSize。location ~ \.php$ { deny all; })。<input type=\"file\" name=\"file[]\" multiple>
使用者可按住 Ctrl/Shift 選取多檔,$_FILES 結構相同,前端體驗更好。