HTML 表單必要條件
<form action="upload.php" method="POST" enctype="multipart/form-data">
<!-- 限制上傳大小 (瀏覽器端提示,不可信) -->
<input type="hidden" name="MAX_FILE_SIZE" value="5242880"> <!-- 5MB -->
<label>選擇檔案:<input type="file" name="upload_file" accept="image/*,.pdf" required></label>
<button type="submit">上傳</button>
</form>
PHP 處理核心流程
<?php
// upload.php
const UPLOAD_DIR = __DIR__ . '/uploads/';
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
const ALLOWED_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
// 確保目錄存在且可寫
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0755, true);
}
$errors = [];
$file = $_FILES['upload_file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
$errorMessages = [
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 => 'PHP 擴展阻止上傳',
];
$errors[] = $errorMessages[$file['error'] ?? '未知錯誤'];
} else {
// 1. 驗證檔案大小
if ($file['size'] > MAX_SIZE) {
$errors[] = "檔案過大 (最大 " . (MAX_SIZE/1024/1024) . "MB)";
}
// 2. 驗證 MIME 類型 (需配合 finfo,不要信任 $_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_TYPES, true)) {
$errors[] = "不允許的檔案類型: $mime";
}
// 3. 驗證副檔名 (雙重保險)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXTS, true)) {
$errors[] = "不允許的副檔名: $ext";
}
// 4. 圖片額外驗證:getimagesize 確認真為圖片
if (str_starts_with($mime, 'image/')) {
$imgInfo = @getimagesize($file['tmp_name']);
if (!$imgInfo) $errors[] = '無效的圖片檔案';
}
}
if ($errors) {
http_response_code(400);
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
// 5. 生成安全檔名 (避免覆蓋、路徑遍歷、特殊字元)
$safeName = bin2hex(random_bytes(16)) . '.' . $ext; // 32 字元隨機 + 副檔名
$destPath = UPLOAD_DIR . $safeName;
// 6. 移動檔案 (從暫存目錄移至目標)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
http_response_code(500);
echo json_encode(['success' => false, 'errors' => ['伺服器儲存失敗']]);
exit;
}
// 7. 可選:設定檔案權限
chmod($destPath, 0644);
// 成功回應
echo json_encode([
'success' => true,
'file' => [
'original_name' => $file['name'],
'saved_name' => $safeName,
'size' => $file['size'],
'mime' => $mime,
'url' => '/uploads/' . $safeName,
]
]);
?>
關鍵安全設定 (php.ini)
; 檔案上傳總開關
file_uploads = On
; 最大上傳檔案大小 (需配合 post_max_size)
upload_max_filesize = 10M
; POST 總資料大小 (需 > upload_max_filesize)
post_max_size = 12M
; 最大檔案數量
max_file_uploads = 20
; 暫存目錄 (確保權限正確)
upload_tmp_dir = /tmp/php_uploads
; 執行時間限制 (大檔案需調大)
max_execution_time = 60
max_input_time = 60
進階主題
分塊上傳 (大檔案斷點續傳)
- 前端:
WebUploader、Uppy、Dropzone.js 切片上傳
- 後端:合併分塊、驗證 MD5、支援續傳
雲端儲存整合
<?php
// AWS S3 範例 (aws/aws-sdk-php)
use Aws\S3\S3Client;
$s3 = new S3Client([
'region' => 'ap-northeast-1',
'version' => 'latest',
'credentials' => ['key' => '...', 'secret' => '...']
]);
$s3->putObject([
'Bucket' => 'my-bucket',
'Key' => 'uploads/' . $safeName,
'SourceFile' => $file['tmp_name'],
'ACL' => 'private',
]);
// 簽名 URL 供前端直傳 (繞過後端流量)
$presignedUrl = $s3->createPresignedRequest(
new \Aws\Command('PutObject', ['Bucket'=>'my-bucket', 'Key'=>'uploads/${filename}']),
'+10 minutes'
)->getUri();
?>
圖片處理管道
- 上傳後佇列任務:縮圖、水印、格式轉換、WebP/AVIF 優化
- 工具:
Intervention Image、spatie/image-optimizer、Imagick