Course contentsShow
← Security
Lesson 984 of 3,05220. Web Security - File Upload and ProcessingFree lesson

Content-Type and MIME Type Enforcement

Validate file types using magic bytes, reject mismatched Content-Types, and implement strict allowlists for permitted formats.

Content-Type and MIME Type Enforcement

What you'll learn: How to validate files using their true binary signatures instead of trusting client-supplied headers, ensuring attackers can't disguise malicious files.


The Problem: Trusting What Users Tell You

When a user uploads a file, their browser sends a Content-Type header (like image/jpeg). But here's the catch: attackers can lie. They can upload a PHP web shell and label it as image/png. If you only check the header, you'll accept malware disguised as harmless content.

Think of it like airport security: you don't trust someone who says "I promise this is just a water bottle"—you scan it to verify.

How to Enforce File Types Properly

Magic Bytes (File Signatures)
Every legitimate file format starts with specific bytes. A JPEG always begins with FF D8 FF, a PNG with 89 50 4E 47. Read the first few bytes of the uploaded file and compare them against known signatures—this reveals the actual file type, not what the client claims.

Reject Mismatched Content-Types
If the magic bytes say "executable" but the Content-Type header says "image/png," reject it immediately. The mismatch is a red flag.

Strict Allowlists
Never use a blocklist ("block .exe files"). Instead, maintain a strict allowlist: "We only accept PNG, JPEG, and PDF files." If the magic bytes don't match your permitted formats, refuse the upload—no exceptions.

Layered Defense

Combine all three techniques:

  1. Check magic bytes match your allowlist
  2. Verify Content-Type header aligns with magic bytes
  3. Validate file extension matches both

This prevents polyglot files (files valid in multiple formats) and format confusion attacks you studied earlier.


Key Takeaway: Never trust client-supplied Content-Type headers—always validate file types using magic byte inspection, enforce strict format allowlists, and reject any mismatches between declared and actual file types.