<form method="post" enctype="multipart/form-data">
<input type="file" name="images[]" multiple accept="image/*">
<button type="submit">上傳</button>
</form>
name="images[] 讓 PHP 接收到多維陣列結構。
<?php
const MAX_FILES = 10;
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_MIME = ['image/jpeg','image/png','image/gif','image/webp'];
const ALLOWED_EXT = ['jpg','jpeg','png','gif','webp'];
$uploadDir = __DIR__ . '/uploads/' . date('Y-m-d') . '/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0775, true);
$results = ['success' => [], 'errors' => []];
$files = $_FILES['images'] ?? [];
// 重組 $_FILES 結構為單檔案陣列
$fileCount = count($files['name']);
for ($i = 0; $i < $fileCount; $i++) {
if ($i >= MAX_FILES) {
$results['errors'][] = "超過最大檔案數 $MAX_FILES";
break;
}
$name = $files['name'][$i];
$tmp = $files['tmp_name'][$i];
$size = $files['size'][$i];
$err = $files['error'][$i];
if ($err !== UPLOAD_ERR_OK) {
$results['errors'][] = "$name: 上傳錯誤碼 $err";
continue;
}
if ($size > MAX_SIZE) {
$results['errors'][] = "$name: 檔案過大 (限制 " . (MAX_SIZE/1024/1024) . "MB)";
continue;
}
// MIME 型別二次驗證(防偽造 Content-Type)
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmp);
finfo_close($finfo);
if (!in_array($mime, ALLOWED_MIME, true)) {
$results['errors'][] = "$name: MIME 型別不允許 ($mime)";
continue;
}
// 副檔名驗證
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXT, true)) {
$results['errors'][] = "$name: 副檔名不允許";
continue;
}
// 安全檔名
$safeName = bin2hex(random_bytes(12)) . '.' . $ext;
$dest = $uploadDir . $safeName;
if (move_uploaded_file($tmp, $dest)) {
$results['success'][] = [
'original' => $name,
'stored' => $safeName,
'path' => str_replace(__DIR__, '', $dest),
'size' => $size,
'mime' => $mime,
];
} else {
$results['errors'][] = "$name: 移動檔案失敗";
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($results, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
document.querySelector('form').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const res = await fetch('upload_multi.php', {method: 'POST', body: formData});
const data = await res.json();
data.success.forEach(f => console.log('成功:', f.path));
data.errors.forEach(err => console.error('失敗:', err));
});
php_flag engine off / Nginx location ~ \.php$ { deny all; }readfile() + 權限檢查)