文件上傳是 Web 開發中常見的功能,正確的實作需注意表單屬性、伺服器端驗證、檔案儲存路徑規劃以及安全性防護。本文透過三個階段完整示範:基本表單提交、處理腳本邏輯、物件導向封裝類別。
上傳表單必須設定 enctype="multipart/form-data" 並使用 method="post",否則 $_FILES 陣列將為空。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>檔案上傳範例</title>
</head>
<body>
<form action="uploadProcess.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>使用者名稱:</td><td><input type="text" name="username"></td></tr>
<tr><td>檔案說明:</td><td><textarea name="fileintro" rows="7" cols="50" style="width:300px;"></textarea></td></tr>
<tr><td>選擇檔案:</td><td><input type="file" name="myfile"></td></tr>
<tr><td colspan="2"><input type="submit" value="上傳"></td></tr>
</table>
</form>
</body>
</html>
處理腳本需執行:接收表單欄位、驗證檔案大小與類型、確認上傳狀態、建立使用者專屬目錄、以時間戳+隨機數重命名防止覆蓋、移動暫存檔案。
<?php
// 接收一般表單欄位
$username = $_POST['username'] ?? '';
$fileintro = $_POST['fileintro'] ?? '';
// 1. 檔案大小限制 (2MB)
$file_size = $_FILES['myfile']['size'] ?? 0;
if ($file_size > 2 * 1024 * 1024) {
exit('<script>alert("檔案不可超過 2MB");</script>');
}
// 2. 檔案類型限制 (僅允許 JPEG)
$file_type = $_FILES['myfile']['type'] ?? '';
if (!in_array($file_type, ['image/jpeg', 'image/pjpeg'])) {
exit('僅允許上傳 JPG 格式圖片');
}
// 3. 確認是否為合法上傳檔案
if (is_uploaded_file($_FILES['myfile']['tmp_name'])) {
$upload_file = $_FILES['myfile']['tmp_name'];
// 建立使用者專屬目錄
$user_path = $_SERVER['DOCUMENT_ROOT'] . '/file/up/' . $username;
if (!file_exists($user_path)) {
mkdir($user_path, 0755, true);
}
// 產生唯一檔名:時間戳 + 隨機數 + 原始副檔名
$orig_name = $_FILES['myfile']['name'];
$ext = substr($orig_name, strrpos($orig_name, '.'));
$new_name = time() . rand(1, 1000) . $ext;
$move_to_file = $user_path . '/' . $new_name;
// 移動檔案 (處理中文檔名編碼)
if (move_uploaded_file($upload_file, iconv('UTF-8', 'GB2312', $move_to_file))) {
echo $orig_name . ' 上傳成功';
} else {
echo '上傳失敗';
}
} else {
echo '非法上傳或上傳失敗';
}
?>
將上傳邏輯封裝為可復用類別,支援多種允許副檔名、自動建立目錄、錯誤處理。
<?php
class Upload {
public $upload_name; // 原始檔名
public $upload_tmp_path; // 暫存路徑
public $file_size; // 檔案大小
public $file_type; // MIME 類型
public $file_save_path; // 儲存根目錄
private $allow_ext = ['jpeg','jpg','png','gif','bmp','doc','zip','rar','txt','wps','xlsx','ppt'];
public function __construct() {
$this->upload_name = $_FILES['myfile']['name'] ?? '';
$this->upload_tmp_path = $_FILES['myfile']['tmp_name'] ?? '';
$this->file_size = $_FILES['myfile']['size'] ?? 0;
$this->file_type = $_FILES['myfile']['type'] ?? '';
$this->file_save_path = $_SERVER['DOCUMENT_ROOT'] . '/file/up/';
}
public function upload_file($username) {
// 大小檢查
if ($this->file_size > 2 * 1024 * 1024) {
exit('<script>alert("檔案不可超過 2MB");</script>');
}
// 副檔名檢查 (比 MIME 類型更可靠)
$ext = strtolower(pathinfo($this->upload_name, PATHINFO_EXTENSION));
if (!in_array($ext, $this->allow_ext)) {
exit('不允許的檔案類型');
}
if (!is_uploaded_file($this->upload_tmp_path)) {
exit('非法上傳');
}
// 建立使用者目錄
$user_dir = $this->file_save_path . $username;
if (!file_exists($user_dir)) {
mkdir($user_dir, 0755, true);
}
// 產生唯一檔名
$new_name = time() . rand(1000, 9999) . '.' . $ext;
$dest = $user_dir . '/' . $new_name;
// 移動檔案
if (move_uploaded_file($this->upload_tmp_path, iconv('UTF-8', 'GB2312', $dest))) {
return ['status' => true, 'message' => '上傳成功', 'path' => $dest];
}
return ['status' => false, 'message' => '上傳失敗'];
}
}
// 使用範例
// $uploader = new Upload();
// $result = $uploader->upload_file($_POST['username']);
// print_r($result);
?>
$_FILES['type'],請改用 pathinfo() 檢查副檔名或 finfo_file() 偵測真實 MIME。random_bytes() 或 uniqid() 產生檔名比 time()+rand() 更安全。