萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檔案上傳完整教學:表單屬性、MIME 對照、多檔上傳、下載處理、HTML 表單元素詳解

檔案上傳表單必要條件

<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副檔名
Texttext/html.html, .htm
text/plain.txt, .log
Imageimage/gif.gif
image/jpeg.jpeg, .jpg
image/png.png
Audioaudio/midi.mid, .midi
audio/wav.wav
Videovideo/quicktime.qt, .mov
video/mpeg.mpeg
Applicationapplication/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>textmaxlength, size, value, placeholder, pattern, required
passwordmaxlength, size
checkboxchecked, value (預設 on)
radioname (同群組), value, checked
submitvalue (按鈕文字)
resetvalue (按鈕文字)
fileaccept (MIME 過濾), multiple, capture
hiddenvalue
imagesrc, 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 模式) 避免重複提交
  • 錯誤訊息友善、具體,保留使用者輸入
copyright © 萬盛學電腦網 all rights reserved