萬盛學電腦網

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

PHP 上傳文件類型驗證三重奏:副檔名白名單、MIME 偵測、檔頭魔數檢查

風險等級對照

方法可靠度繞過難度備註
副檔名檢查極低改副檔名即可繞過僅作第一道防線
$_FILES['type'] (MIME)低瀏覽器根據副檔名猜測,可偽造不可信任
finfo_file (檔頭魔數)高需構造合法檔頭推薦核心驗證
圖片重繪 (GD/Imagick)最高極難繞過處理圖片上傳必做

完整驗證類實作

class UploadValidator {
    private array $allowedExt  = ['jpg','jpeg','png','gif','webp','pdf','docx'];
    private array $allowedMime = [
        'jpg'  => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png'  => 'image/png',
        'gif'  => 'image/gif',
        'webp' => 'image/webp',
        'pdf'  => 'application/pdf',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ];

    public function validate(array $file): string {
        // 1. 錯誤碼檢查
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception("上傳錯誤代碼: {$file['error']}");
        }

        // 2. 副檔名白名單
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $this->allowedExt, true)) {
            throw new Exception("副檔名 $ext 不在允許清單");
        }

        // 3. 檔頭魔數驗證 (finfo)
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime  = $finfo->file($file['tmp_name']);
        if (($this->allowedMime[$ext] ?? null) !== $mime) {
            throw new Exception("檔案類型不符: 期望 {$this->allowedMime[$ext]}, 實際 $mime");
        }

        // 4. 圖片額外驗證:嘗試重繪,剝離隱藏腳本
        if (str_starts_with($mime, 'image/')) {
            $img = @imagecreatefromstring(file_get_contents($file['tmp_name']));
            if (!$img) throw new Exception("圖片損壞或非真實圖片");
            // 重新編碼存儲,移除 EXIF/註釋
            imagejpeg($img, $file['tmp_name'], 90);
            imagedestroy($img);
        }

        // 5. 檔案大小限制 (例 5MB)
        if ($file['size'] > 5 * 1024 * 1024) {
            throw new Exception("檔案過大");
        }

        return $ext; // 返回驗證通過的副檔名
    }
}

使用範例

$validator = new UploadValidator();
try {
    $ext = $validator->validate($_FILES['avatar']);
    $dest = "/uploads/" . bin2hex(random_bytes(16)) . ".$ext";
    move_uploaded_file($_FILES['avatar']['tmp_name'], $dest);
    echo "上傳成功: $dest";
} catch (Exception $e) {
    echo "失敗: " . $e->getMessage();
}

關鍵安全提醒

  • 儲存路徑不可直接 Web 訪問,或配置 Nginx location ~ \.php$ { deny all; } 禁止執行。
  • 檔名使用隨機雜湊(random_bytes),防止覆蓋、遍歷、特殊字符注入。
  • 資料庫儲存相對路徑,不儲存用戶原始檔名。
  • 定期掃描上傳目錄異常文件(find /uploads -type f -name "*.php*")。
copyright © 萬盛學電腦網 all rights reserved