表單需設定 `enctype="multipart/form-data"`,單檔上傳時結構如下:
$_FILES['myFile'] = [
'name' => 'photo.jpg', // 客戶端原始檔名
'type' => 'image/jpeg', // MIME 類型 (瀏覽器提供,不可信)
'tmp_name' => '/tmp/phpA1B2C3', // 伺服器暫存路徑
'size' => 123456, // 檔案大小 (bytes)
'error' => 0, // 錯誤代碼
];
| 常量 | 值 | 說明 |
|---|---|---|
| UPLOAD_ERR_OK | 0 | 上傳成功 |
| UPLOAD_ERR_INI_SIZE | 1 | 超過 php.ini `upload_max_filesize` |
| UPLOAD_ERR_FORM_SIZE | 2 | 超過表單 `MAX_FILE_SIZE` 隱藏欄位 |
| UPLOAD_ERR_PARTIAL | 3 | 僅部分上傳 (網路中斷) |
| UPLOAD_ERR_NO_FILE | 4 | 未選擇檔案 |
| UPLOAD_ERR_NO_TMP_DIR | 6 | 缺少暫存目錄 (PHP 5.0.3+) |
| UPLOAD_ERR_CANT_WRITE | 7 | 寫入磁碟失敗 (PHP 5.1.0+) |
| UPLOAD_ERR_EXTENSION | 8 | 擴展阻止上傳 (PHP 5.2.0+) |
<?php
function handleUpload(array $file, string $uploadDir, array $allowedMimes = []): array
{
// 1. 錯誤檢查
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('上傳錯誤代碼: ' . $file['error']);
}
// 2. MIME 驗證 (使用 finfo,不可信 $_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if ($allowedMimes && !in_array($mime, $allowedMimes, true)) {
throw new RuntimeException('檔案類型不允許: ' . $mime);
}
// 3. 檔案大小二次檢查
if ($file['size'] > 5 * 1024 * 1024) { // 5MB
throw new RuntimeException('檔案過大');
}
// 4. 產生安全檔名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$allowedExt = ['jpg','jpeg','png','gif','webp','pdf'];
if (!in_array($ext, $allowedExt, true)) {
throw new RuntimeException('副檔名不允許');
}
$newName = bin2hex(random_bytes(16)) . '.' . $ext;
$destPath = $uploadDir . DIRECTORY_SEPARATOR . $newName;
// 5. 移動檔案 (不可用 copy+unlink)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
throw new RuntimeException('移動檔案失敗');
}
// 6. 圖片二次渲染清理 (可選)
if (str_starts_with($mime, 'image/')) {
$im = imagecreatefromstring(file_get_contents($destPath));
if ($im) {
imagewebp($im, $destPath, 85);
imagedestroy($im);
}
}
return ['path' => $destPath, 'name' => $newName, 'mime' => $mime, 'size' => $file['size']];
}
?>
<?php
//
foreach ($_FILES['files']['error'] as $key => $error) {
if ($error === UPLOAD_ERR_OK) {
$single = [
'name' => $_FILES['files']['name'][$key],
'type' => $_FILES['files']['type'][$key],
'tmp_name' => $_FILES['files']['tmp_name'][$key],
'size' => $_FILES['files']['size'][$key],
'error' => $error,
];
try {
$result = handleUpload($single, __DIR__.'/uploads', ['image/jpeg','image/png','image/webp']);
echo "成功: {$result['name']}
";
} catch (Throwable $e) {
echo "失敗: {$e->getMessage()}
";
}
}
}
?>
file_uploads = On upload_max_filesize = 10M post_max_size = 12M max_file_uploads = 20 upload_tmp_dir = /var/tmp/php-upload ; 確保目錄存在且 www-data 可寫