萬盛學電腦網

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

PHP 圖片上傳至指定目錄並存入 MySQL 完整實作教學

專案架構概覽

本範例包含四個檔案,示範從表單上傳、檔案驗證、重新命名、儲存至目錄,到將路徑寫入 MySQL 的完整流程:

  • conn.php:資料庫連線設定
  • upload.php:前端表單與後端接收邏輯
  • uploadclass.php:檔案上傳核心類別 (型別檢查、隨機命名、移動檔案)
  • SQL 匯出檔:建立 upload 資料表結構與範例資料

關鍵程式碼解析

1. 資料庫連線 (conn.php) — ⚠️ 使用已棄用 mysql_* 函式

$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 編碼。

2. 上傳處理類別 (uploadclass.php) 核心邏輯

// 允許副檔名
$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
    }
}

3. 表單與入口 (upload.php)

<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);
}

資料表結構 (SQL 匯出)

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) 統一儲存抽象層。

copyright © 萬盛學電腦網 all rights reserved