本類封裝了圖片上傳的完整流程:檔案驗證(類型、副檔名、大小、HTTP 上傳)、目錄自動建立、唯一檔名生成、以及基於 GD 庫的等比例縮略圖產生。適合快速整合至專案中。
class Upload {
protected $fileMine, $filepath, $filemax, $fileExt, $filename, $fileerror, $fileflag, $fileinfo, $ext, $path;
public function __construct($filename="file", $filemax=20000000, $filepath="./Uploads", $fileflag=true, $fileExt=array('jpg','png','gif'), $fileMine=array('image/jpeg','image/png','image/gif')) {
$this->filename = $filename;
$this->fileinfo = $_FILES[$this->filename];
$this->filemax = $filemax;
$this->filepath = $filepath;
$this->fileflag = $fileflag;
$this->fileExt = $fileExt;
$this->fileMine = $fileMine;
}
// 錯誤碼對照表
public function UpError() { /* ... */ }
// MIME 類型檢查
public function UpMine() { /* ... */ }
// 副檔名檢查
public function UpExt() { /* ... */ }
// 目錄檢查/建立
public function UpPath() { /* ... */ }
// 檔案大小檢查
public function UpSize() { /* ... */ }
// 是否為 HTTP POST 上傳
public function UpPost() { /* ... */ }
// 生成唯一檔名
public function Upname() { return md5(uniqid(microtime(true), true)); }
// 縮略圖生成 (等比例縮放)
public function Smallimg($x=100, $y=100) {
$imgAtt = getimagesize($this->path);
$imgWidth = $imgAtt[0]; $imgHeight = $imgAtt[1]; $imgext = $imgAtt[2];
$bl = ($x/$imgWidth > $y/$imgHeight) ? $y/$imgHeight : $x/$imgWidth;
$newW = floor($imgWidth * $bl);
$newH = floor($imgHeight * $bl);
$dstImg = imagecreatetruecolor($newW, $newH);
$srcImg = imagecreatefromjpeg($this->path); // 示範 JPEG,實際應依 $imgext 切換
imagecopyresampled($dstImg, $srcImg, 0,0,0,0, $newW,$newH, $imgWidth,$imgHeight);
imagejpeg($dstImg, $this->path); // 覆蓋原檔或另存新檔
imagedestroy($dstImg); imagedestroy($srcImg);
}
// 執行上傳流程
public function uploads() {
if ($this->UpError() && $this->UpMine() && $this->UpExt() && $this->UpSize() && $this->UpPost()) {
$this->UpPath();
$this->path = $this->filepath . '/' . $this->Upname() . '.' . $this->ext;
if (move_uploaded_file($this->fileinfo['tmp_name'], $this->path)) {
return $this->path;
}
$this->fileerror = "移動檔案失敗";
}
exit("{$this->fileerror}");
}
}
// 接收表單上傳
$u = new Upload('file', 2000000, './Uploads', true, array('jpg','png','gif'), array('image/jpeg','image/png','image/gif'));
$savedPath = $u->uploads(); // 回傳儲存路徑
$u->Smallimg(150, 150); // 生成 150x150 縮略圖 (覆蓋原圖)
echo "
"; // 顯示結果