Application Security

Validate File Uploads Beyond Their File Extensions

Combine size limits, content inspection, storage isolation and safe processing for untrusted uploaded files.

A filename extension is only a hint supplied by the client. An attacker can rename an executable file to look like an image or submit content that exploits a parser. Upload handling should treat every file as untrusted until it has passed validation and safe storage steps.

Validate the request and file

Enforce request and file size limits at the web server and PHP layers. Check upload error codes, inspect the detected media type and verify that the file can be parsed by the intended library. For images, decode and re-encode when appropriate rather than trusting the original bytes.

Generate server-side names

Do not use the original filename as a storage path. Generate a random identifier, store the original display name separately after safe normalization and prevent path traversal. Avoid overwriting existing files based on user-controlled names.

Store outside executable paths

Keep private uploads outside the public document root when possible. If public access is required, use a dedicated static location with script execution disabled and safe response headers. Serve private files through an authorization-aware download handler.

Process defensively

Limit image dimensions, archive expansion, document pages and parser execution time. Keep file-processing libraries updated and consider quarantine or malware scanning for higher-risk workflows.

Checklist

  • Enforce size and request limits.
  • Inspect content rather than trusting extensions.
  • Generate opaque server-side filenames.
  • Store uploads outside executable web paths.
  • Bound parser resources and protect downloads.
Share this page Help other developers discover this resource.