enctype="multipart/form-data" + method="POST"move_uploaded_file)<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" name="userfile">
<input type="submit" value="上傳">
</form>
enctype="multipart/form-data":必須,讓伺服器識別二進位檔案資料。MAX_FILE_SIZE:客戶端限制(可被繞過),伺服端仍需驗證。| 鍵名 | 說明 |
|---|---|
| name | 客戶端原始檔名 |
| type | MIME 類型(如 image/jpeg) |
| size | 檔案大小(位元組) |
| tmp_name | 伺服器暫存路徑 |
| error | 錯誤代碼(0=成功,1=超過 php.ini 上限,2=超過表單上限,3=部分上傳,4=無檔案) |
move_uploaded_file($tmp, $dest):將暫存檔移至目標路徑(必須使用此函式,確保安全)。is_uploaded_file($tmp):確認檔案確為 HTTP 上傳。<?php
function uploadFile($type, $name, $ext, $size, $error, $tmpName, $targetName, $uploadDir) {
$MAX_SIZE = 2_000_000; // 2MB
$ALLOWED_MIMES = ['image/jpeg', 'image/png', 'image/gif'];
$ALLOWED_EXTS = ['.jpg', '.jpeg', '.png', '.gif'];
// 1. 確保上傳目錄存在且可寫
if (!is_dir($uploadDir)) {
if (!mkdir($uploadDir, 0755, true)) {
die('無法建立上傳目錄');
}
}
// 2. 基本驗證
if ($size > $MAX_SIZE) die('檔案過大');
if ($size === 0) die('請選擇檔案');
if (!in_array($type, $ALLOWED_MIMES) || !in_array(strtolower($ext), $ALLOWED_EXTS)) {
die('不允許的檔案類型');
}
$targetPath = $uploadDir . '/' . $targetName;
// 3. 移動檔案
if (!move_uploaded_file($tmpName, $targetPath)) {
die('檔案移動失敗');
}
// 4. 錯誤代碼處理
switch ($error) {
case 0: return true;
case 1: die('超過 php.ini upload_max_filesize');
case 2: die('超過表單 MAX_FILE_SIZE');
case 3: die('檔案部分上傳');
case 4: die('未上傳檔案');
default: die('未知錯誤');
}
}
?>
表單 name="files[]" 多個 <input type="file" name="files[]">,PHP 端 $_FILES['files']['name'][0] 為第一個檔案,以此類推。
| 指令 | 建議值 | 說明 |
|---|---|---|
| file_uploads | On | 啟用 HTTP 上傳 |
| upload_max_filesize | 32M | 單一檔案上限 |
| post_max_size | 32M | POST 總資料上限(必須 ≥ upload_max_filesize) |
| max_execution_time | 600 | 腳本最長執行秒數 |
| max_input_time | 600 | 接收資料最長秒數 |
| memory_limit | 128M | 腳本記憶體上限 |
| upload_tmp_dir | /tmp | 暫存目錄(需可寫) |
move_uploaded_file() 而非 copy() 或 rename()。$_FILES['type'],可用 finfo_file() 偵測真實 MIME。檔案上傳看似簡單,實則涉及安全、效能、相容性多重考量,建議封裝為可復用的上傳服務類別。