萬盛學電腦網

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

PHP 多檔案上傳類完整實作與安全加固指南

功能完整的多檔案上傳類設計

本文重構一個生產級的 MultipleFileUpload 類,涵蓋檔案類型驗證(MIME + 魔術位元組)、大小限制、隨機重命名、錯誤處理、總大小統計等核心功能,並修正原始碼中的語法錯誤與安全隱患。

核心功能清單

  • 支援單次上傳多個檔案($_FILES 陣列處理)
  • 雙重驗證:MIME 類型 + 檔頭魔術位元組(防偽造)
  • 自動偵測圖片真實格式(JPG/GIF/PNG/BMP)
  • 隨機檔名(MD5 + uniqid + microtime)防衝突
  • 上傳目錄自動建立、權限檢查
  • 詳細錯誤代碼對應訊息(UPLOAD_ERR_* 常數)
  • 檔案大小人性化顯示(B/KB/MB)

完整類別程式碼

<?php
class MultipleFileUpload
{
    private const UPLOAD_DIR = __DIR__ . '/../uploads/';
    private const MAX_TOTAL_SIZE = 20 * 1024 * 1024; // 20MB 總限制
    private const MAX_FILE_SIZE  = 5 * 1024 * 1024;  // 5MB 單檔限制

    // 允許的 MIME 類型
    private const ALLOWED_MIME = [
        'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'
    ];

    // 魔術位元組簽名(十六進位字串)
    private const MAGIC_BYTES = [
        'image/jpeg' => 'ffd8ff',
        'image/png'  => '89504e47',
        'image/gif'  => '47494638',
        'image/bmp'  => '424d',
        'image/webp' => '52494646', // RIFF header, 需進一步檢查 WEBP
    ];

    private array $results = [];
    private int $totalSize = 0;

    public function handleUpload(array $files): array
    {
        $this->validateUploadDir();
        $this->processFiles($files);
        return $this->results;
    }

    private function validateUploadDir(): void
    {
        if (!is_dir(self::UPLOAD_DIR)) {
            if (!mkdir(self::UPLOAD_DIR, 0755, true) && !is_dir(self::UPLOAD_DIR)) {
                throw new RuntimeException('無法建立上傳目錄: ' . self::UPLOAD_DIR);
            }
        }
        if (!is_writable(self::UPLOAD_DIR)) {
            throw new RuntimeException('上傳目錄不可寫入: ' . self::UPLOAD_DIR);
        }
    }

    private function processFiles(array $files): void
    {
        // 正規化 $_FILES 結構
        $normalized = $this->normalizeFilesArray($files);

        foreach ($normalized as $file) {
            if ($this->totalSize >= self::MAX_TOTAL_SIZE) {
                $this->addResult($file['name'], '超過總容量限制', false);
                continue;
            }
            $this->processSingleFile($file);
        }
    }

    private function normalizeFilesArray(array $files): array
    {
        $normalized = [];
        foreach ($files as $key => $value) {
            if (isset($value['name']) && is_array($value['name'])) {
                // 多檔案欄位:name="files[]"
                $count = count($value['name']);
                for ($i = 0; $i < $count; $i++) {
                    $normalized[] = [
                        'name'     => $value['name'][$i],
                        'type'     => $value['type'][$i],
                        'tmp_name' => $value['tmp_name'][$i],
                        'error'    => $value['error'][$i],
                        'size'     => $value['size'][$i],
                    ];
                }
            } else {
                // 單檔案欄位
                $normalized[] = $value;
            }
        }
        return $normalized;
    }

    private function processSingleFile(array $file): void
    {
        $name = $file['name'];
        $error = $file['error'];
        $size = $file['size'];
        $tmp = $file['tmp_name'];
        $mime = $file['type'];

        // 1. PHP 內建錯誤代碼檢查
        if ($error !== UPLOAD_ERR_OK) {
            $this->addResult($name, $this->getUploadErrorMessage($error), false);
            return;
        }

        // 2. 檔案大小檢查
        if ($size > self::MAX_FILE_SIZE) {
            $this->addResult($name, "檔案大小超過 " . $this->formatBytes(self::MAX_FILE_SIZE), false);
            return;
        }

        // 3. MIME 類型白名單
        if (!in_array($mime, self::ALLOWED_MIME, true)) {
            $this->addResult($name, "不允許的檔案類型: $mime", false);
            return;
        }

        // 4. 魔術位元組驗證(核心安全防禦)
        if (!$this->verifyMagicBytes($tmp, $mime)) {
            $this->addResult($name, "檔案內容與宣告類型不符,疑似偽造", false);
            return;
        }

        // 5. 移動檔案
        $newName = $this->generateRandomName($name);
        $dest = self::UPLOAD_DIR . $newName;

        if (move_uploaded_file($tmp, $dest)) {
            @chmod($dest, 0644);
            $this->totalSize += $size;
            $this->addResult($name, "上傳成功", true, [
                'stored_name' => $newName,
                'size'        => $size,
                'size_fmt'    => $this->formatBytes($size),
                'mime'        => $mime,
                'path'        => $dest,
            ]);
        } else {
            $this->addResult($name, "檔案移動失敗(權限或磁碟空間)", false);
        }
    }

    private function verifyMagicBytes(string $tmpPath, string $mime): bool
    {
        $expectedHex = self::MAGIC_BYTES[$mime] ?? '';
        if (!$expectedHex) return true; // 未定義簽名則跳過

        $fp = fopen($tmpPath, 'rb');
        if (!$fp) return false;
        $header = fread($fp, 12); // 讀足夠長度
        fclose($fp);

        $fileHex = bin2hex($header);
        return str_starts_with(strtolower($fileHex), strtolower($expectedHex));
    }

    private function generateRandomName(string $originalName): string
    {
        $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        $ext = $ext ? '.' . $ext : '';
        return bin2hex(random_bytes(16)) . $ext;
    }

    private 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 . ')',
        };
    }

    private function formatBytes(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, 1) . ' ' . $units[$i];
    }

    private function addResult(string $origName, string $message, bool $success, array $meta = []): void
    {
        $this->results[] = array_merge([
            'original_name' => $origName,
            'message'       => $message,
            'success'       => $success,
        ], $meta);
    }
}

使用範例

<?php
require_once 'MultipleFileUpload.php';

$uploader = new MultipleFileUpload();
$results = $uploader->handleUpload($_FILES['gallery'] ?? []);

foreach ($results as $r) {
    if ($r['success']) {
        printf("✅ %s → %s (%s)%s", $r['original_name'], $r['stored_name'], $r['size_fmt'], PHP_EOL);
    } else {
        printf("❌ %s → %s%s", $r['original_name'], $r['message'], PHP_EOL);
    }
}

HTML 表單範例

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="gallery[]" multiple accept="image/*">
    <button type="submit">上傳圖片</button>
</form>

安全加固清單

  1. 禁用上傳目錄腳本執行:Nginx/Apache 設定 location ~ \.php$ { deny all; }。
  2. 檔案名稱儲存於資料庫,勿直接使用使用者提供的檔名。
  3. 病毒掃描整合:生產環境建議整合 ClamAV 掃描上傳檔案。
  4. 限制並發上傳數:配合 max_file_uploads (php.ini) 與前端 JS 限制。
copyright © 萬盛學電腦網 all rights reserved