檔案上傳表單必要條件
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" name="myfile">
<input type="submit" value="上傳">
</form>
$_FILES 結構與錯誤代碼
參見前文詳細表格。關鍵:error === UPLOAD_ERR_OK (0) 才處理。
MIME 類型完整對照表
| 大類 | MIME | 副檔名 |
| Text | text/html | .html, .htm |
| text/plain | .txt, .log |
| Image | image/gif | .gif |
| image/jpeg | .jpeg, .jpg |
| image/png | .png |
| Audio | audio/midi | .mid, .midi |
| audio/wav | .wav |
| Video | video/quicktime | .qt, .mov |
| video/mpeg | .mpeg |
| Application | application/pdf | .pdf |
| application/msword | .doc, .dot |
| application/vnd.ms-excel | .xls |
| application/vnd.ms-powerpoint | .ppt |
| application/zip | .zip |
| application/rar | .rar |
| application/xml | .xml, .xsl |
| application/mshelp | .hlp, .chm |
| application/octet-stream | .bin, .exe, .dll, .class |
核心函數
is_uploaded_file($tmp_name):驗證是否為 HTTP 上傳檔案
move_uploaded_file($tmp_name, $dest):移動暫存檔到目標位置
多檔案上傳
<input type="file" name="files[]" multiple>
// PHP
foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
$file = [
'name' => $_FILES['files']['name'][$i],
'type' => $_FILES['files']['type'][$i],
'tmp_name' => $tmp,
'error' => $_FILES['files']['error'][$i],
'size' => $_FILES['files']['size'][$i],
];
if ($file['error'] === UPLOAD_ERR_OK) {
// 驗證、移動...
}
}
檔案下載處理
function downloadFile(string $filePath, string $filename = '') {
if (!is_file($filePath)) { http_response_code(404); exit; }
$filename = $filename ?: basename($filePath);
$size = filesize($filePath);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . $size);
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
readfile($filePath); // 直接輸出,不佔記憶體
exit;
}
HTML 表單元素完整屬性速查
| 標籤 | type 值 | 關鍵屬性 |
| <input> | text | maxlength, size, value, placeholder, pattern, required |
| password | maxlength, size |
| checkbox | checked, value (預設 on) |
| radio | name (同群組), value, checked |
| submit | value (按鈕文字) |
| reset | value (按鈕文字) |
| file | accept (MIME 過濾), multiple, capture |
| hidden | value |
| image | src, alt, width, height |
| button | 無預設行為,配合 JS |
| <select> | - | name, size, multiple, required |
| <option> | - | value, selected, disabled |
| <textarea> | - | name, rows, cols, wrap (off/hard/soft), maxlength, placeholder |
| <form> | - | action, method, enctype, name, target, onsubmit, onreset |
表單處理最佳實務
- 後端**永遠驗證**,前端驗證僅為 UX
- 使用 CSRF Token 保護 POST 表單
- 檔案上傳目錄設定不可執行腳本
- 上傳成功後重導向 (PRG 模式) 避免重複提交
- 錯誤訊息友善、具體,保留使用者輸入