security

Upload Security

Core Controls

  • Enforce size limits before expensive processing.
  • Detect allowed file types from content where possible; do not trust extension or browser MIME type alone.
  • Generate storage names in application code and keep originals as display metadata only.
  • Store private files outside the public web root or in private object storage.
  • Scan or isolate files when the business risk justifies it.

Validate Metadata And Content

Browser-supplied filenames and MIME types are hints, not proof. Inspect the upload result, enforce a size limit, and detect the MIME type from the temporary file where possible.

PHP example
<?php

declare(strict_types=1);

function allowedImageMime(string $mime): bool
{
    return in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true);
}

var_dump(allowedImageMime('image/png'));
var_dump(allowedImageMime('application/x-php'));

// Prints:
// bool(true)
// bool(false)

For images, decode and re-encode when the product allows it. Check dimensions before expensive processing because a small compressed file can expand significantly in memory.

Generate Storage Names

Use an application-generated key such as a random identifier. Keep the original filename only as escaped display metadata.

Private files belong outside the public web root or in private object storage. Serve them through an authorised download path or a short-lived signed URL.

Treat Processing As A Boundary

Image libraries, PDF tools, archive extractors, and antivirus scanners parse hostile bytes. Keep them updated, limit CPU and memory, and isolate risky processing where the product threat model requires it.

In Application Work

Image libraries, document converters, archive extraction, and antivirus scanners add their own attack surface. Keep them updated and process risky files with restricted permissions.

What To Check

Before moving on, make sure you can validate upload status, size, detected type, and dimensions; generate storage keys; keep private files non-public; and test malformed and oversized files.

Practice

Practice: Review A Profile Image Upload

Requirements

  • Allow only required image formats and sizes.
  • Generate a random storage key.
  • Keep the original filename as metadata only.
  • Describe private storage and later serving rules.
Show solution

Review Points

  • Enforce size limits before expensive processing.
  • Detect allowed file types from content where possible; do not trust extension or browser MIME type alone.
  • Generate storage names in application code and keep originals as display metadata only.
  • Store private files outside the public web root or in private object storage.
  • Scan or isolate files when the business risk justifies it.