萬盛學電腦網

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

PHP 多圖片上傳類完整實作:型別驗證、魔術位元組檢測、隨機命名、單位轉換

封裝良好的上傳類別能統一處理驗證、儲存、錯誤回報,提升專案可維護性。本文提供一個功能完整的 MultipleFileUpload 類別,支援多檔案、型別白名單、魔術位元組真實型別檢測、大小限制、自動建立目錄、B/KB/MB 單位轉換。

完整類別代碼

<?php
class MultipleFileUpload {
    // 設定常數
    public const DEFAULT_PATH = '/uploads/';
    public const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    
    // 允許的 MIME 型別(擴充性佳)
    protected array $allowedMimes = [
        'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/webp',
        'application/pdf', 'text/plain',
    ];
    
    // 魔術位元組簽名(檔案真實型別驗證)
    protected array $magicSignatures = [
        'gif'  => [0x47, 0x49, 0x46],           // GIF87a/89a
        'jpg'  => [0xFF, 0xD8, 0xFF],           // JPEG
        'png'  => [0x89, 0x50, 0x4E, 0x47],    // PNG
        'webp' => [0x52, 0x49, 0x46, 0x46],    // RIFF (WebP)
        'pdf'  => [0x25, 0x50, 0x44, 0x46],    // %PDF
    ];
    
    // 實例屬性
    protected string $savePath;
    protected int $maxSize;
    protected array $errors = [];
    protected array $success = [];
    protected int $totalSize = 0;
    
    public function __construct(string $savePath = '', int $maxSize = 0) {
        $this->savePath = $savePath ?: self::DEFAULT_PATH;
        $this->maxSize = $maxSize ?: self::MAX_FILE_SIZE;
        
        // 確保目錄存在
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0755, true);
        }
    }
    
    /**
     * 處理 $_FILES 陣列
     * @param array $files $_FILES['userfile'] 結構
     * @return array ['success'=>[], 'errors'=>[], 'total_size'=>int]
     */
    public function handle(array $files): array {
        $this->errors = [];
        $this->success = [];
        $this->totalSize = 0;
        
        // 正規化 $_FILES 結構(支援單檔與多檔兩種格式)
        $normalized = $this->normalizeFilesArray($files);
        
        foreach ($normalized as $index => $file) {
            $result = $this->processSingleFile($file, $index);
            if ($result['success']) {
                $this->success[] = $result;
                $this->totalSize += $result['size'];
            } else {
                $this->errors[] = $result;
            }
        }
        
        return [
            'success' => $this->success,
            'errors' => $this->errors,
            'total_size' => $this->totalSize,
            'total_count' => count($this->success),
        ];
    }
    
    /**
     * 正規化 $_FILES 為單一檔案陣列
     * 處理單檔:['name'=>'a.jpg', 'tmp_name'=>'...', ...]
     * 處理多檔:['name'=>['a.jpg','b.jpg'], 'tmp_name'=>['...','...'], ...]
     */
    protected function normalizeFilesArray(array $files): array {
        // 如果是單檔結構(無數字鍵),包裝為陣列
        if (!isset($files['name'][0])) {
            return [$files];
        }
        
        // 多檔結構:轉置陣列
        $count = count($files['name']);
        $normalized = [];
        for ($i = 0; $i < $count; $i++) {
            $normalized[] = [
                'name' => $files['name'][$i],
                'type' => $files['type'][$i],
                'tmp_name' => $files['tmp_name'][$i],
                'error' => $files['error'][$i],
                'size' => $files['size'][$i],
            ];
        }
        return $normalized;
    }
    
    protected function processSingleFile(array $file, int $index): array {
        // 1. 上傳錯誤碼檢查
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return $this->error($index, $file['name'], $this->getUploadErrorMessage($file['error']));
        }
        
        // 2. 檔案大小檢查
        if ($file['size'] > $this->maxSize) {
            return $this->error($index, $file['name'], "檔案大小超過限制 ({$this->formatSize($this->maxSize)})");
        }
        
        // 3. MIME 型別白名單檢查(瀏覽器提供,可偽造)
        if (!in_array($file['type'], $this->allowedMimes, true)) {
            return $this->error($index, $file['name'], "MIME 型別不允許: {$file['type']}");
        }
        
        // 4. 魔術位元組真實型別檢測(核心安全防線)
        if (!$this->verifyMagicBytes($file['tmp_name'], $file['type'])) {
            return $this->error($index, $file['name'], "檔案內容與宣稱型別不符,疑似偽造");
        }
        
        // 5. 產生安全檔名
        $ext = $this->getSafeExtension($file['name'], $file['type']);
        $newName = $this->generateSafeName($ext);
        $destPath = $this->savePath . $newName;
        
        // 6. 移動檔案
        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            return $this->error($index, $file['name'], "檔案移動失敗,請檢查目錄權限");
        }
        
        // 7. 成功回傳
        return [
            'success' => true,
            'index' => $index,
            'original_name' => $file['name'],
            'saved_name' => $newName,
            'path' => $destPath,
            'size' => $file['size'],
            'size_formatted' => $this->formatSize($file['size']),
            'mime' => $file['type'],
        ];
    }
    
    // 魔術位元組驗證
    protected function verifyMagicBytes(string $tmpPath, string $declaredMime): bool {
        $fp = fopen($tmpPath, 'rb');
        $header = fread($fp, 12); // 讀取前 12 位元組足夠
        fclose($fp);
        
        if ($header === false || strlen($header) < 4) return false;
        
        $bytes = array_values(unpack('C*', $header));
        
        // 對應 MIME 到簽名
        $mimeToSig = [
            'image/gif' => 'gif',
            'image/jpeg' => 'jpg',
            'image/pjpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'application/pdf' => 'pdf',
        ];
        
        $sigKey = $mimeToSig[$declaredMime] ?? '';
        if (!$sigKey) return true; // 未定義簽名的型別跳過檢測
        
        $expected = $this->magicSignatures[$sigKey];
        foreach ($expected as $i => $byte) {
            if (!isset($bytes[$i]) || $bytes[$i] !== $byte) return false;
        }
        return true;
    }
    
    // 取得安全副檔名
    protected function getSafeExtension(string $filename, string $mime): string {
        $extMap = [
            'image/gif' => 'gif',
            'image/jpeg' => 'jpg',
            'image/pjpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'application/pdf' => 'pdf',
            'text/plain' => 'txt',
        ];
        return $extMap[$mime] ?? strtolower(pathinfo($filename, PATHINFO_EXTENSION) ?: 'bin');
    }
    
    // 產生唯一檔名
    protected function generateSafeName(string $ext): string {
        return bin2hex(random_bytes(16)) . '.' . $ext;
    }
    
    // 格式化大小
    protected function formatSize(int $bytes): string {
        if ($bytes < 1024) return "{$bytes} B";
        if ($bytes < 1024*1024) return round($bytes/1024, 1) . " KB";
        if ($bytes < 1024*1024*1024) return round($bytes/1024/1024, 2) . " MB";
        return round($bytes/1024/1024/1024, 2) . " GB";
    }
    
    // 錯誤訊息對照
    protected function getUploadErrorMessage(int $code): string {
        return match ($code) {
            UPLOAD_ERR_INI_SIZE => '超過 php.ini upload_max_filesize',
            UPLOAD_ERR_FORM_SIZE => '超過表單 MAX_FILE_SIZE',
            UPLOAD_ERR_PARTIAL => '檔案僅部分上傳',
            UPLOAD_ERR_NO_FILE => '未選擇檔案',
            UPLOAD_ERR_NO_TMP_DIR => '缺少臨時目錄',
            UPLOAD_ERR_CANT_WRITE => '寫入磁碟失敗',
            UPLOAD_ERR_EXTENSION => '被 PHP 擴展阻擋',
            default => "未知錯誤代碼: {$code}",
        };
    }
    
    // 統一錯誤格式
    protected function error(int $index, string $name, string $msg): array {
        return [
            'success' => false,
            'index' => $index,
            'original_name' => $name,
            'error' => $msg,
        ];
    }
}

使用範例

<?php
require 'MultipleFileUpload.php';

$uploader = new MultipleFileUpload('/var/www/uploads/', 10 * 1024 * 1024); // 10MB

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = $uploader->handle($_FILES['userfile']);
    
    header('Content-Type: application/json');
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}
?>
<form method="post" enctype="multipart/form-data">
    <input type="file" name="userfile[]" multiple>
    <button type="submit">上傳</button>
</form>

回傳 JSON 結構範例

{
    "success": [
        {
            "success": true,
            "index": 0,
            "original_name": "photo.jpg",
            "saved_name": "a1b2c3d4e5f678901234567890abcdef.jpg",
            "path": "/var/www/uploads/a1b2c3d4e5f678901234567890abcdef.jpg",
            "size": 245760,
            "size_formatted": "240.0 KB",
            "mime": "image/jpeg"
        }
    ],
    "errors": [],
    "total_size": 245760,
    "total_count": 1
}

擴充建議

  • 圖片處理:整合 Intervention/Image 自動產生縮圖、水印、WebP 轉換
  • 雲端儲存:實作 StorageAdapterInterface,切換 Local/S3/OSS/MinIO
  • 病毒掃描:整合 ClamAV clamscan 掃描暫存檔
  • 斷點續傳:前端 Uppy + 後端分片合併
  • 非同步佇列:大檔案丟入 Redis Queue,Worker 處理後回調
copyright © 萬盛學電腦網 all rights reserved