首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 檔案上傳與圖片處理完整類庫:驗證、重命名、縮略圖、水印(文字/圖片)

     編輯:PHP 綜合知識

類架構總覽

  • uploadFile:基礎上傳類,支援類型/大小驗證、自動建目錄、多種命名策略。
  • uploadImg extends uploadFile:圖片專用,繼承上傳功能,新增縮略圖、水印(英文/中文/圖片 Logo)。

核心功能與代碼亮點

1. 靈活配置建構子

public function __construct($save_path = './upload/', $file_name = 'date', $allow_types = '') {
    $this->save_path = rtrim($save_path, '/') . '/';
    $this->file_name = $file_name; // 'date' 表時間命名,其他視為固定檔名
    $this->allow_types = $allow_types ?: 'jpg|gif|png|zip|rar';
    $this->max_size = 1000000; // 1MB 預設
}

2. 完整錯誤碼對應($_FILES['error'])

case 1: $this->errmsg = '超過 php.ini upload_max_filesize'; break;
case 2: $this->errmsg = '超過表單 MAX_FILE_SIZE'; break;
case 3: $this->errmsg = '檔案部分上傳'; break;
case 4: $this->errmsg = '未選擇檔案'; break;
case 5: $this->errmsg = '檔案大小為 0'; break;

3. 類型驗證:副檔名白名單 + 可擴展 MIME 檢查

public function check_file_type($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $allow = explode('|', $this->allow_types);
    if (!in_array($ext, $allow)) {
        $this->errmsg = "類型錯誤,允許: " . implode(',', $allow);
        return false;
    }
    $this->ext = $ext;
    return true;
}
// 建議補充:getimagesize() 或 finfo_file() 驗證真實 MIME

4. 安全移動與權限

if (move_uploaded_file($tmp_name, $this->uploaded)) {
    @chmod($this->uploaded, 0644); // 檔案權限
    $this->errmsg = "上傳成功: {$this->uploaded}";
    return true;
}

圖片處理進階功能

縮略圖生成

public function img_resized($w, $h, $source_img = null) {
    $source_img = $source_img ?? $this->uploaded;
    $src = $this->img_create($source_img); // 依 MIME 建立 image resource
    $thumb = imagecreatetruecolor($w, $h);
    imagecopyresampled($thumb, $src, 0,0,0,0, $w,$h, $src_w,$src_h); // 高品質重採樣
    $dst = $this->set_newname($source_img); // 寬_高_原檔名
    $this->img_output($thumb, $dst);
    imagedestroy($src); imagedestroy($thumb);
}

**關鍵**:使用 imagecopyresampled 而非 imagecopyresized,品質顯著提升。

水印支援三種模式

類型方法適用場景
英文字串imagestring()簡單版權標記、無需字體檔
中文字串imagettftext() + TTF 字體中文水印、需 SIMSUN.TTC 等字體
圖片 Logoimagecopy() 疊加 PNG品牌 Logo、透明背景、視覺效果佳

九宮格定位邏輯

private function get_mark_xy($pos) {
    // $pos: 1=左下 2=右下 3=左上 4=右上
    // 根據圖片尺寸、水印尺寸計算座標
    // 考慮 imagestring (左上基準) vs imagettftext (左下基準) 差異
}

使用範例

// 1. 一般檔案上傳
$uploader = new uploadFile('./uploads/', 'date', 'jpg|png|pdf');
if ($uploader->upload_file($_FILES['file'])) {
    echo "檔案路徑: {$uploader->uploaded}";
} else {
    echo "錯誤: {$uploader->errmsg}";
}

// 2. 圖片上傳 + 縮略圖 + 中文水印
$img = new uploadImg('./uploads/', 'date', 'jpg|png|gif');
$img->mark_str = '版權所有 © 2024';
$img->mark_ttf = '/fonts/msjh.ttc'; // 微軟正黑體
$img->str_r = 255; $img->str_g = 255; $img->str_b = 255; // 白色

if ($img->upload_file($_FILES['photo'])) {
    $img->img_resized(300, 200);           // 生成 300x200 縮略圖
    $img->img_mark(null, 2, 2);            // 右下角中文水印
    echo "處理完成";
}

安全加固建議(生產環境必做)

  1. MIME 二次驗證:finfo_file(fopen($tmp, 'r'), FILEINFO_MIME_TYPE) 對照白名單。
  2. 檔名去敏感化:上傳後以 md5(uniqid()) . '.' . $ext 重命名,避免路徑遍歷、覆蓋。
  3. 儲存目錄非 Web 可執行:上傳目錄設 php_flag engine off 或放在 public/ 外。
  4. 限制圖片尺寸:getimagesize() 檢查寬高,防止解壓縮炸彈。
  5. 病毒掃描:整合 ClamAV 掃描上傳檔案。

總結

此類庫涵蓋從基礎上傳驗證到圖片縮略、水印的完整鏈路,代碼結構清晰、繼承關係合理。實務部署時務必疊加上述安全層,並考慮遷移至雲端儲存(S3/OSS)+ 圖片處理服務以應對高併發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved