多檔案上傳是 PHP 基礎應用。關鍵在於 HTML 表單的 name 屬性加上 [] 形成陣列,PHP 透過 $_FILES 超全域變數接收。本文從原理、陣列結構、完整範例三方面詳細說明。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="pictures[]"><br>
<input type="file" name="pictures[]"><br>
<input type="file" name="pictures[]"><br>
<input type="submit" value="上傳">
</form>
enctype="multipart/form-data":必須設定,否則檔案不會上傳。name="pictures[]":方括號讓 PHP 將同名輸入組成陣列。Array
(
[pictures] => Array
(
[name] => Thumbs.db
[type] => application/octet-stream
[tmp_name] => D:\EasyPHP\tmp\php64.tmp
[error] => 0
[size] => 23040
)
)
Array
(
[pictures] => Array
(
[name] => Array
(
[0] => file1.txt
[1] => file2.txt
[2] => file3.txt
)
[type] => Array
(
[0] => application/octet-stream
[1] => application/octet-stream
[2] => application/octet-stream
)
[tmp_name] => Array
(
[0] => D:\EasyPHP\tmp\php47.tmp
[1] => D:\EasyPHP\tmp\php48.tmp
[2] => D:\EasyPHP\tmp\php49.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[size] => Array
(
[0] => 94289
[1] => 65536
[2] => 102400
)
)
)
| 索引 | 含義 |
|---|---|
name | 用戶端原始檔名 |
type | MIME 類型(瀏覽器提供,不可完全信任) |
tmp_name | 伺服器暫存路徑 |
error | 錯誤代碼:0=成功,1=超過 php.ini upload_max_filesize,2=超過表單 MAX_FILE_SIZE,3=部分上傳,4=未上傳檔案 |
size | 檔案大小(位元組) |
<?php
// 簡易驗證與搬移
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
$files = $_FILES['pictures'];
$count = count($files['name']);
$success = 0;
for ($i = 0; $i < $count; $i++) {
if ($files['error'][$i] !== UPLOAD_ERR_OK) {
echo "檔案 {$files['name'][$i]} 上傳失敗,錯誤碼:{$files['error'][$i]}<br>";
continue;
}
// 簡易副檔名檢查
$ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg','jpeg','png','gif','pdf'])) {
echo "檔案 {$files['name'][$i]} 類型不允許<br>";
continue;
}
// 產生唯一檔名避免覆蓋
$newName = uniqid('img_', true) . ".{$ext}";
$dest = $uploadDir . $newName;
if (move_uploaded_file($files['tmp_name'][$i], $dest)) {
echo "檔案 {$files['name'][$i]} 上傳成功,儲存為 {$newName}<br>";
$success++;
} else {
echo "檔案 {$files['name'][$i]} 移動失敗<br>";
}
}
echo "共成功上傳 {$success} 個檔案。";
?>
file_uploads=On、upload_max_filesize、post_max_size(需大於 upload_max_filesize)、max_file_uploads(預設 20,限制單次上傳檔案數)。<input type="hidden" name="MAX_FILE_SIZE" value="2097152">(2MB),僅為客戶端提示,伺服端仍需驗證 $_FILES['error']。$files['error'][$i],針對不同錯誤碼給予友善提示。現代專案建議採用 FormData + fetch/XHR 非同步上傳,配合 xhr.upload.onprogress 顯示進度,伺服端邏輯不變,僅將 $_FILES 來源從表單提交改為 AJAX 請求。
掌握 name="files[]" 形成陣列、$_FILES 三維結構、move_uploaded_file() 搬移暫存檔、檔名安全重命名、php.ini 相關設定,即可扎實掌握 PHP 多檔案上傳核心技術。