HTML 表單必要條件
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000"> <!-- 2MB,瀏覽器端提示,非強制 -->
<input type="file" name="myfile">
<input type="submit" value="上傳">
</form>
method="post":檔案上傳必須用 POST
enctype="multipart/form-data":編碼類型,必須設定
MAX_FILE_SIZE:隱藏欄位,建議值,瀏覽器可能攔截過大檔案
$_FILES 結構解析
$_FILES['myfile'] = [
'name' => 'original.jpg', // 客戶端原始檔名
'type' => 'image/jpeg', // 瀏覽器提供的 MIME (不可信)
'tmp_name' => '/tmp/phpXyZ123', // 伺服器暫存路徑
'error' => UPLOAD_ERR_OK, // 錯誤代碼
'size' => 123456 // 檔案大小 (bytes)
];
錯誤代碼對照
| 常數 | 值 | 說明 |
| 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 | 缺少暫存目錄 |
| UPLOAD_ERR_CANT_WRITE | 7 | 寫入磁碟失敗 |
| UPLOAD_ERR_EXTENSION | 8 | 擴充套件中止 |
安全驗證清單 (必要)
function validateUpload($file, array $allowedTypes = [], int $maxSize = 2000000): array {
// 1. 檢查錯誤代碼
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception("上傳錯誤代碼: {$file['error']}");
}
// 2. 檢查檔案大小
if ($file['size'] > $maxSize) {
throw new Exception("檔案過大,最大 $maxSize bytes");
}
// 3. 檢查 MIME 型別 (使用 finfo,不信任 $_FILES['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if ($allowedTypes && !in_array($mime, $allowedTypes, true)) {
throw new Exception("不允許的檔案類型: $mime");
}
// 4. 檢查副檔名 (雙重保險)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
if (!in_array($ext, $allowedExt, true)) {
throw new Exception("不允許的副檔名: $ext");
}
// 5. 檢查是否真為上傳檔案
if (!is_uploaded_file($file['tmp_name'])) {
throw new Exception("非合法上傳檔案");
}
return ['mime' => $mime, 'ext' => $ext];
}
移動檔案與命名策略
function moveUploadedFile(array $file, string $uploadDir, string $prefix = ''): string {
// 確保目錄存在
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 產生安全檔名:時間戳 + 隨機字串 + 原始副檔名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$newName = $prefix . date('YmdHis') . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
$destPath = $uploadDir . DIRECTORY_SEPARATOR . $newName;
// 移動 (僅接受上傳檔案,防止路徑遍歷)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
throw new Exception("移動檔案失敗");
}
// 設定適當權限
chmod($destPath, 0644);
return $destPath;
}
完整上傳處理流程
<?php
// upload.php
$uploadDir = __DIR__ . '/uploads';
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
$maxSize = 5 * 1024 * 1024; // 5MB
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('無效請求方法');
}
if (!isset($_FILES['myfile'])) {
throw new Exception('缺少檔案欄位');
}
$file = $_FILES['myfile'];
$info = validateUpload($file, $allowedTypes, $maxSize);
$savedPath = moveUploadedFile($file, $uploadDir, 'upload_');
echo json_encode(['success' => true, 'path' => $savedPath, 'mime' => $info['mime']]);
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
多檔案上傳
<input type="file" name="files[]" multiple>
// PHP 處理
foreach ($_FILES['files']['tmp_name'] as $index => $tmpName) {
$file = [
'name' => $_FILES['files']['name'][$index],
'type' => $_FILES['files']['type'][$index],
'tmp_name' => $tmpName,
'error' => $_FILES['files']['error'][$index],
'size' => $_FILES['files']['size'][$index],
];
// 逐個驗證與移動...
}
大檔案上傳考量
- php.ini:
upload_max_filesize, post_max_size, max_execution_time, memory_limit
- 分塊上傳:前端切片,後端合併 (WebUploader, Uppy, Dropzone)
- 進度顯示:Session 上傳進度 (
session.upload_progress) 或 AJAX 輪詢
- 雲端直傳:預簽名 URL 直傳 S3/OSS,減輕伺服器負載