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

PHP 圖片上傳類實現:支持縮略圖生成、類型驗證、防重命名

     編輯:PHP 綜合知識

功能特性

  • 文件類型/MIME/擴展名/大小多重驗證
  • 上傳目錄自動創建
  • MD5+Microtime 防重命名
  • 支持 JPEG 縮略圖等比縮放生成
  • 面向對象封裝,易擴展

核心類代碼 (list.php)

<?php
class Upload {
    protected $fileMine;   // 允許 MIME
    protected $filepath;   // 上傳目錄
    protected $filemax;    // 最大字節
    protected $fileExt;    // 允許擴展名
    protected $filename;   // $_FILES 鍵名
    protected $fileerror;  // 錯誤信息
    protected $fileflag;   // 是否檢測
    protected $fileinfo;   // $_FILES 數據
    protected $ext;        // 解析出的擴展名
    protected $path;       // 最終存儲路徑

    public function __construct($filename="file", $filemax=20000000, $filepath="./Uploads",
                                $fileflag=true, $fileExt=array('jpg','jpeg','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() {
        if ($this->fileinfo['error'] > 0) {
            $msg = [
                1 => '超過 php.ini upload_max_filesize',
                2 => '超過表單 MAX_FILE_SIZE',
                3 => '文件部分上傳',
                4 => '未選擇文件',
                5 => '臨時目錄不存在',
                6 => '寫入失敗',
                7 => '擴展未啟用',
                8 => ''
            ];
            $this->fileerror = $msg[$this->fileinfo['error']] ?? '未知錯誤';
            return false;
        }
        return true;
    }

    // MIME 檢測
    public function UpMine() {
        if (!in_array($this->fileinfo['type'], $this->fileMine)) {
            $this->fileerror = "MIME 類型不允許";
            return false;
        }
        return true;
    }

    // 擴展名檢測
    public function UpExt() {
        $this->ext = strtolower(pathinfo($this->fileinfo['name'], PATHINFO_EXTENSION));
        if (!in_array($this->ext, $this->fileExt)) {
            $this->fileerror = "擴展名不允許";
            return false;
        }
        return true;
    }

    // 目錄檢測/創建
    public function UpPath() {
        if (!file_exists($this->filepath)) mkdir($this->filepath, 0777, true);
    }

    // 大小檢測
    public function UpSize() {
        if ($this->fileinfo['size'] > $this->filemax) {
            $this->fileerror = "文件過大";
            return false;
        }
        return true;
    }

    // 是否 HTTP POST 上傳
    public function UpPost() {
        if (!is_uploaded_file($this->fileinfo['tmp_name'])) {
            $this->fileerror = "非法上傳";
            return false;
        }
        return true;
    }

    // 生成唯一文件名
    public function Upname() {
        return md5(uniqid(microtime(true), true));
    }

    // 縮略圖生成 (僅 JPEG 示例,可擴展 PNG/GIF)
    public function Smallimg($x=100, $y=100) {
        $info = getimagesize($this->path);
        $w = $info[0]; $h = $info[1]; $type = $info[2];
        $scale = min($x/$w, $y/$h);
        $nw = floor($w*$scale); $nh = floor($h*$scale);
        $dst = imagecreatetruecolor($nw, $nh);
        $src = imagecreatefromjpeg($this->path);
        imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $w,$h);
        imagejpeg($dst, $this->path); // 覆蓋原圖或另存新路徑
        imagedestroy($dst); imagedestroy($src);
    }

    // 執行上傳
    public function uploads() {
        if ($this->UpError() && $this->UpMine() && $this->UpExt() && $this->UpSize() && $this->UpPost()) {
            $this->UpPath();
            $name = $this->Upname();
            $this->path = $this->filepath . '/' . $name . '.' . $this->ext;
            if (move_uploaded_file($this->fileinfo['tmp_name'], $this->path)) {
                return $this->path;
            }
            $this->fileerror = "移動失敗";
        }
        exit("{$this->fileerror}");
    }
}
?>

使用示例 (ce.php)

<?php
header("Content-Type: text/html; charset=utf-8");
require 'list.php';

$u = new Upload();
$original = $u->uploads();        // 上傳原圖
$u->Smallimg(200, 150);           // 生成縮略圖 (覆蓋原路徑)
echo "<img src='{$original}' />"; // 顯示
?>

前端表單 (HTML)

<form action="ce.php" enctype="multipart/form-data" method="post">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="submit" name="submit" value="提交" />
</form>

效果圖

驗證碼效果圖

改進建議

  1. 縮略圖不應覆蓋原圖,建議生成 {$name}_thumb.{$ext}
  2. 增加 PNG/GIF 透明度保持邏輯
  3. 引入 Imagick 擴展替代 GD 獲得更好性能與格式支持
  4. 上傳後記錄資料庫(原名、存儲名、路徑、大小、MIME、上傳時間)
  5. 異步上傳:前端 FormData + AJAX + 進度條
  6. 安全:禁用腳本執行權限、病毒掃描、存儲雲端 (OSS/S3)

總結

本類封裝了上傳驗證、存儲、命名、縮略圖核心流程,代碼結構清晰,適合作為項目基礎組件進一步擴展。生產環境請務必加強安全防護與異常處理。

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