uploadFile:基礎上傳類,支援類型/大小驗證、自動建目錄、多種命名策略。uploadImg extends uploadFile:圖片專用,繼承上傳功能,新增縮略圖、水印(英文/中文/圖片 Logo)。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 預設
}
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;
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
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 等字體 |
| 圖片 Logo | imagecopy() 疊加 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 "處理完成";
}
finfo_file(fopen($tmp, 'r'), FILEINFO_MIME_TYPE) 對照白名單。md5(uniqid()) . '.' . $ext 重命名,避免路徑遍歷、覆蓋。php_flag engine off 或放在 public/ 外。getimagesize() 檢查寬高,防止解壓縮炸彈。此類庫涵蓋從基礎上傳驗證到圖片縮略、水印的完整鏈路,代碼結構清晰、繼承關係合理。實務部署時務必疊加上述安全層,並考慮遷移至雲端儲存(S3/OSS)+ 圖片處理服務以應對高併發。