前端表單 (HTML)
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880"> <!-- 5MB 客戶端提示 -->
<label>標題: <input type="text" name="title" required></label><br>
<label>選擇圖片: <input type="file" name="image" accept="image/*" required></label><br>
<button type="submit">上傳</button>
</form>
後端處理 (upload.php) - 生產級完整版
<?php
// 配置
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const ALLOWED_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
const UPLOAD_ROOT = __DIR__ . '/uploads';
// 1. 檢查請求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit('僅支援 POST');
}
// 2. 檢查錯誤碼
if (($error = $_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
$messages = [
UPLOAD_ERR_INI_SIZE => '超過 php.ini 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 => '被擴展中斷',
];
exit('上傳錯誤: ' . ($messages[$error] ?? '未知錯誤'));
}
// 3. 檢查檔案大小 (雙重保險)
if ($_FILES['image']['size'] > MAX_SIZE) {
exit('檔案過大,限制 ' . (MAX_SIZE/1024/1024) . 'MB');
}
// 4. 驗證 MIME 類型 (使用 finfo,不可信任 $_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['image']['tmp_name']);
if (!in_array($mime, ALLOWED_TYPES, true)) {
exit('不允許的檔案類型: ' . $mime);
}
// 5. 驗證副檔名
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXTS, true)) {
exit('不允許的副檔名: ' . $ext);
}
// 6. 進階:檢查圖片真實性 (防偽裝腳本)
$imgInfo = @getimagesize($_FILES['image']['tmp_name']);
if (!$imgInfo || !in_array($imgInfo[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
exit('檔案非有效圖片或已損壞');
}
// 7. 生成安全儲存路徑:年/月/日 + 隨機檔名
$dateDir = date('Y/m/d');
$saveDir = UPLOAD_ROOT . '/' . $dateDir;
if (!is_dir($saveDir)) {
if (!mkdir($saveDir, 0755, true)) {
exit('無法建立上傳目錄');
}
}
$filename = bin2hex(random_bytes(16)) . '.' . $ext; // 32 字元隨機檔名
$savePath = $saveDir . '/' . $filename;
// 8. 移動檔案 (move_uploaded_file 會檢查是否為上傳檔案)
if (!move_uploaded_file($_FILES['image']['tmp_name'], $savePath)) {
exit('移動檔案失敗,請檢查權限');
}
// 9. 設定權限 (可選)
chmod($savePath, 0644);
// 10. 返回結果 (JSON 供 AJAX,或重導向)
$webPath = '/uploads/' . $dateDir . '/' . $filename;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
header('Content-Type: application/json');
echo json_encode(['success'=>true, 'path'=>$webPath, 'filename'=>$filename]);
} else {
header('Location: success.php?img=' . urlencode($webPath));
}
exit;
安全加固清單
- 禁用執行權限:上傳目錄配置 Nginx/Apache 禁止執行 PHP/腳本。
# Nginx
location /uploads/ {
location ~ \.php$ { deny all; return 403; }
}
- 檔名隨機化:防止覆蓋、路徑遍歷、猜測。
- MIME 雙重驗證:
finfo + getimagesize()。
- 大小限制雙層:PHP
upload_max_filesize/post_max_size + 代碼邏輯檢查。
- 病毒掃描:高安全場景整合 ClamAV (
clamscan) 異步掃描。
- CDN/對象存儲:生產環境建議直傳 S3/OSS,避免佔用應用伺服器頻寬與磁碟。
常見錯誤排查
| 現象 | 可能原因 | 排查 |
| $_FILES 為空 | form 缺少 enctype、post_max_size 過小 | 檢查 HTML、php.ini |
| move_uploaded_file 失敗 | 目錄權限、磁碟滿、open_basedir 限制 | 檢查 chown www-data、df -h、php.ini |
| 上傳後無法訪問 | Nginx 禁止執行、路徑錯誤、防盜鏈 | 檢查 location 配置、權限、Referer 策略 |