Lesson 6 of 9 · 25m
File Uploads: Validate, Rename, Isolate, Serve Carefully
Uploads combine content attacks, parser attacks, path attacks, and execution attacks — the safe design treats every file as hostile cargo.
A file upload feature is not one feature. It is a malware ingestion pipeline connected to your filesystem, image decoders, PDF readers, antivirus tooling, backup jobs, and sometimes your PHP interpreter. The correct posture is containment: accept only what you can identify, store it where it cannot execute, and serve it in a way that browsers cannot reinterpret.
Never trust the client metadata
$_FILES['avatar']['type'] and the original filename are supplied by the client. They are hints, not facts. Use them for UX, not authorization.
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($tmpPath);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
if (!isset($allowed[$mime])) reject_upload('Unsupported image type');Constrain size and shape before storage
PHP limits matter, but application limits should be tighter and explicit:
upload_max_filesize = 5M
post_max_size = 6MStore outside execution reach
The ideal upload path is outside the web root and on storage that cannot execute PHP:
$extension = $allowed[$mime];
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$destination = '/srv/app-uploads/' . substr($name, 0, 2) . '/' . $name;
if (!move_uploaded_file($tmpPath, $destination)) {
throw new RuntimeException('Upload storage failed');
}Serve through a controlled path
A controlled download endpoint sets explicit headers:
header('Content-Type: ' . $mime);
header('X-Content-Type-Options: nosniff');
header('Content-Disposition: inline; filename="avatar-' . $id . '.' . $extension . '"');
header('Cache-Control: private, max-age=3600');
readfile($path);For untrusted documents, attachment is often safer than inline display. Configure nginx so the upload path never executes PHP and always sends nosniff; better yet, keep uploads outside any application-server location entirely.
Archives and office formats are loaders
A ZIP is not a file; it is a container full of paths, compression ratios, symlinks, and nested formats. If you extract archives, do it in a sandbox with size limits, file-count limits, path sanitization, and no permission to write outside a scratch directory. XML files can carry entity-expansion and external-entity attacks depending on the parser. PDFs are miniature programs to some viewers.
Field notes
- Scanning with ClamAV or a vendor engine can catch known malware, but scanner failure must mean quarantine or rejection, never silent approval.
move_uploaded_file()is not optional for HTTP uploads; it verifies the file actually came through PHP's upload mechanism.- If using object storage, keep the same discipline: random keys, private buckets, signed download URLs, strict content types.
- Test upload behavior with double extensions, uppercase extensions, wrong MIME bytes, huge dimensions, and files containing valid image bytes plus appended payload data.
Was this lesson helpful?