檔案上傳是 Web 應用常見功能,但也是高風險攻擊面(惡意腳本上傳、路徑遍歷、DoS、檔案型別偽造)。本文提供從前端表單、PHP 處理、安全驗證、錯誤處理、儲存策略到效能優化的完整指南。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" accept="image/*,.pdf">
<button type="submit">上傳</button>
</form>
enctype="multipart/form-data":必須,否則 $_FILES 為空accept:客戶端過濾 (僅 UX,不可信任)multiple:允許多檔上傳 name="files[]"<?php
// 單檔:$_FILES['myfile']
// 多檔:$_FILES['files'] = ['name'=>[...], 'type'=>[...], 'tmp_name'=>[...], 'error'=>[...], 'size'=>[...]]
$file = $_FILES['myfile'];
/*
[
'name' => 'photo.jpg', // 客戶端原始檔名 (不可信)
'type' => 'image/jpeg', // 客戶端 MIME (不可信)
'tmp_name' => '/tmp/phpA1B2C3', // 伺服器暫存路徑 (唯一可信)
'error' => 0, // 錯誤代碼 (0=成功)
'size' => 204800, // 檔案大小 (bytes)
'full_path' => 'path/photo.jpg' // PHP 8.1+ 完整路徑 (webkitdirectory)
]
*/
| 常數 | 值 | 說明 |
|---|---|---|
UPLOAD_ERR_OK | 0 | 上傳成功 |
UPLOAD_ERR_INI_SIZE | 1 | 超過 upload_max_filesize (php.ini) |
UPLOAD_ERR_FORM_SIZE | 2 | 超過表單 MAX_FILE_SIZE 隱藏欄位 |
UPLOAD_ERR_PARTIAL | 3 | 部分上傳 (網路中斷) |
UPLOAD_ERR_NO_FILE | 4 | 未選擇檔案 |
UPLOAD_ERR_NO_TMP_DIR | 6 | 缺少暫存目錄 |
UPLOAD_ERR_CANT_WRITE | 7 | 寫入磁碟失敗 |
UPLOAD_ERR_EXTENSION | 8 | PHP 擴充阻止上傳 |
<?php
// upload.php
declare(strict_types=1);
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const ALLOWED_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
const UPLOAD_DIR = __DIR__ . '/uploads/';
function uploadFile(array $file): array {
// 1. 檢查錯誤
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception(uploadErrorMessage($file['error']));
}
// 2. 檢查大小
if ($file['size'] > MAX_SIZE) {
throw new Exception("檔案過大 (限制 " . (MAX_SIZE/1024/1024) . "MB)");
}
// 3. 檢查 MIME (使用 finfo,不可信 $_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_TYPES, true)) {
throw new Exception("不支援的檔案類型: $mime");
}
// 4. 檢查副檔名 (雙重保險)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXTS, true)) {
throw new Exception("不允許的副檔名: $ext");
}
// 5. 檢查圖片真實性 (防偽造 MIME)
if (str_starts_with($mime, 'image/')) {
$imgInfo = getimagesize($file['tmp_name']);
if ($imgInfo === false) {
throw new Exception("非有效圖片檔案");
}
// 可選:檢查寬高限制
// if ($imgInfo[0] > 4000 || $imgInfo[1] > 4000) throw new Exception('圖片尺寸過大');
}
// 6. 生成安全檔名 (防路徑遍歷、覆蓋、資訊洩露)
$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$destPath = UPLOAD_DIR . $safeName;
// 7. 移動檔案 (atomic move,跨檔案系統也安全)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
throw new Exception("檔案移動失敗");
}
// 8. 設定權限 (僅擁有者可讀寫)
chmod($destPath, 0640);
return [
'original_name' => $file['name'],
'stored_name' => $safeName,
'path' => $destPath,
'url' => '/uploads/' . $safeName, // 相對 Web 根目錄
'size' => $file['size'],
'mime' => $mime,
'width' => $imgInfo[0] ?? null,
'height' => $imgInfo[1] ?? null,
];
}
function uploadErrorMessage(int $code): string {
return match($code) {
UPLOAD_ERR_INI_SIZE => '檔案超過伺服器限制 (upload_max_filesize)',
UPLOAD_ERR_FORM_SIZE => '檔案超過表單限制 (MAX_FILE_SIZE)',
UPLOAD_ERR_PARTIAL => '檔案上傳不完整',
UPLOAD_ERR_NO_FILE => '未選擇檔案',
UPLOAD_ERR_NO_TMP_DIR => '伺服器暫存目錄遺失',
UPLOAD_ERR_CANT_WRITE => '檔案寫入失敗',
UPLOAD_ERR_EXTENSION => '被 PHP 擴充阻擋',
default => "未知上傳錯誤 (代碼: $code)"
};
}
// 處理請求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$result = uploadFile($_FILES['myfile']);
echo json_encode(['success' => true, 'data' => $result], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
exit;
}
?>
$_FILES['name']、type 皆可偽造。唯一可信:tmp_name (伺服器暫存路徑)$_FILES['type']../../etc/passwd)、資訊洩露# Nginx
location /uploads/ {
location ~ \.php$ { deny all; return 403; }
}
# Apache .htaccess
<FilesMatch "\.php$">
Require all denied
</FilesMatch>
upload_max_filesize, post_max_size, MAX_FILE_SIZE (隱藏欄位,客戶端可繞過)uploads/2024/06/15/{random}.ext 避免單目錄檔案過多<?php
// HTML:
$files = $_FILES['files'];
$results = [];
$errors = [];
$count = count($files['name']);
for ($i = 0; $i < $count; $i++) {
$file = [
'name' => $files['name'][$i],
'type' => $files['type'][$i],
'tmp_name' => $files['tmp_name'][$i],
'error' => $files['error'][$i],
'size' => $files['size'][$i],
];
try {
$results[] = uploadFile($file);
} catch (Exception $e) {
$errors[] = ['file' => $file['name'], 'error' => $e->getMessage()];
}
}
echo json_encode(['success' => empty($errors), 'data' => $results, 'errors' => $errors], JSON_UNESCAPED_UNICODE);
| 指令 | 預設值 | 建議值 | 說明 |
|---|---|---|---|
| file_uploads | On | On | 啟用檔案上傳 |
| upload_max_filesize | 2M | 10M~50M | 單檔最大值 |
| post_max_size | 8M | > upload_max_filesize | POST 總大小,需大於單檔限制 |
| max_file_uploads | 20 | 20~100 | 單次請求最大檔案數 |
| upload_tmp_dir | 系統預設 | /var/tmp/php_upload | 指定專用暫存目錄,設定權限 1777 (sticky bit) |
| max_execution_time | 30 | 60~300 | 大檔上傳需更久 |
| max_input_time | 60 | 60~300 | 解析 POST 資料時間 |
| memory_limit | 128M | 256M+ | 處理大圖片 (GD/Imagick) 需更多記憶體 |
tus-php (TUS 協定)、uppy/php-backendaws/aws-sdk-php, google/cloud-storage, aliyuncs/oss-sdk-php<?php
// 上傳後自動處理:縮圖、WebP 轉換、水印、優化
// 使用 intervention/image (GD/Imagick)
$img = Image::make($destPath);
$img->fit(800, 600)->encode('webp', 80)->save($destPath . '.webp');
// 生成縮圖
$img->fit(200, 200)->save(UPLOAD_DIR . 'thumbs/' . $safeName);
enctype="multipart/form-data"tmp_name,使用 finfo 驗證 MIMEgetimagesize()遵循這份指南,能構建安全、可靠、可擴展的檔案上傳系統。