本範例包含四個檔案,示範從表單上傳、檔案驗證、重新命名、儲存至目錄,到將路徑寫入 MySQL 的完整流程:
conn.php:資料庫連線設定upload.php:前端表單與後端接收邏輯uploadclass.php:檔案上傳核心類別 (型別檢查、隨機命名、移動檔案)upload 資料表結構與範例資料$conn = mysql_connect("localhost", "root", "1721");
mysql_query("SET character_set_connection=gb2312, character_set_results=gb2312, character_set_client=binary", $conn);
mysql_select_db("database", $conn);
現代化建議:改用 mysqli 或 PDO,並採用 utf8mb4 編碼。
// 允許副檔名
$type = array("jpg","gif","bmp","jpeg","png");
$uploaddir = "upfiles/";
// 取得副檔名
function fileext($filename) {
return substr(strrchr($filename, '.'), 1);
}
// 產生隨機檔名 (避免衝突)
function random($length) {
$hash = 'CR-';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
// 驗證型別 → 產生唯一檔名 → 移動檔案
$a = strtolower(fileext($_FILES['file']['name']));
if (!in_array($a, $type)) { /* 錯誤處理 */ }
else {
do {
$filename[0] = random(10);
$name = implode(".", $filename);
$uploadfile = $uploaddir . $name;
} while (file_exists($uploadfile));
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
// 成功:顯示預覽、回傳路徑供 upload.php 寫入 DB
}
}
<form method="post" action="?action=save" enctype="multipart/form-data">
<input name="title" type="text" />
<input name="file" type="file" />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input type="submit" name="upload" value="上傳" />
</form>
if ($_GET['action'] == "save") {
include_once('conn.php');
include_once('uploadclass.php');
// $uploadfile 由 uploadclass.php 產生為全域變數 (不推薦)
$sql = "insert into upload(title,pic) values('$title','$pic')";
mysql_query($sql, $conn);
}
CREATE TABLE `upload` (
`uploadid` int(11) unsigned NOT NULL auto_increment,
`title` varchar(50) NOT NULL,
`pic` varchar(50) NOT NULL,
PRIMARY KEY (`uploadid`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
| 問題 | 風險 | 改善方案 |
|---|---|---|
mysql_* 函式 | PHP 7.0+ 已移除 | 改用 PDO::prepare() + 參數綁定 |
| SQL 直接拼接變數 | SQL Injection | 預處理語句 |
| 僅檢查副檔名 | 可上傳偽裝惡意檔案 | 加驗 MIME (finfo_file)、二進位簽章、禁用執行權限 |
隨機檔名依賴 mt_rand | 可預測性 | 改用 random_bytes() + bin2hex |
| 編碼為 gb2312 | 中文支援不全、表情符號無法儲存 | 全鏈路 utf8mb4 |
| 目錄權限 0777 | 任意腳本執行風險 | 目錄設 open_basedir、Nginx/Apache 禁用 PHP 執行 |
本範例展示了傳統 PHP 上傳流程的基本骨架,適合初學者理解檔案處理與資料庫互動。實務專案請務必套用上述安全強化措施,並考慮引入成熟套件 (如 league/flysystem) 統一儲存抽象層。