文件上傳是Web應用高風險功能點。本文提供生產級上傳處理流程:MIME驗證、大小限制、隨機文件名、存儲目錄權限、防止直接訪問執行,並對比常見不安全寫法。
// 危險:直接使用用戶文件名、未驗證類型、可直接訪問執行
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
<?php
// 配置常量
const UPLOAD_ROOT = __DIR__ . '/../data/uploads/'; // 非Web可訪問目錄
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_MIMES = [
'image/jpeg', 'image/png', 'image/gif', 'image/webp',
'application/pdf',
];
const ALLOWED_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
function handle_upload(array $file): array {
// 1. 錯誤碼檢查
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException(upload_error_message($file['error']));
}
// 2. 大小限制
if ($file['size'] > MAX_SIZE) {
throw new RuntimeException('文件超過大小限制');
}
// 3. MIME類型驗證(finfo優於$_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_MIMES, true)) {
throw new RuntimeException('文件類型不允許: ' . $mime);
}
// 4. 副檔名驗證(雙重保險)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXTS, true)) {
throw new RuntimeException('副檔名不允許: ' . $ext);
}
// 5. 生成隨機文件名防衝突、防遍歷
$filename = bin2hex(random_bytes(16)) . '.' . $ext;
// 6. 日期分目錄存儲
$dateDir = date('Y/m/d');
$targetDir = UPLOAD_ROOT . $dateDir;
if (!is_dir($targetDir)) {
mkdir($targetDir, 0750, true); // 僅擁有者和組可寫
}
$targetPath = $targetDir . '/' . $filename;
// 7. 移動文件(原子操作)
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
throw new RuntimeException('文件移動失敗');
}
// 8. 設置權限(去除執行位)
chmod($targetPath, 0640);
return [
'path' => $targetPath,
'url' => '/uploads/' . $dateDir . '/' . $filename, // 經由PHP腳本代理下載
'mime' => $mime,
'size' => $file['size'],
'original_name' => $file['name'],
];
}
function upload_error_message(int $code): string {
return match($code) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => '文件超過大小限制',
UPLOAD_ERR_PARTIAL => '文件上傳不完整',
UPLOAD_ERR_NO_FILE => '未選擇文件',
UPLOAD_ERR_NO_TMP_DIR => '服務器臨時目錄缺失',
UPLOAD_ERR_CANT_WRITE => '寫入臨時文件失敗',
UPLOAD_ERR_EXTENSION => 'PHP擴展阻止上傳',
default => '未知上傳錯誤',
};
}
/data/uploads)。location /uploads { location ~ \.php$ { deny all; } }。readfile()或X-Sendfile/X-Accel-Redirect輸出。if (str_starts_with($mime, 'image/')) {
$img = imagecreatefromstring(file_get_contents($targetPath));
if ($img) {
imagejpeg($img, $targetPath, 85); // 重新壓縮,剝離潛在惡意數據
imagedestroy($img);
}
}
遵循「不信任用戶輸入、最小權限、深度防禦」原則,構建安全可靠的文件上傳服務。