Insights / Security
File type validation for user uploads: why MIME types lie and how to check what a file really is
The browser's Content-Type header and the file extension are both supplied by the uploader — and both can lie. How to validate what a file really is, with magic bytes, decoding, and safe serving.
Kiran Bandarupalli · 20 Nov 2026 · 5 min read

Your upload form asks the browser what kind of file it is sending, and the browser answers with whatever the uploader told it: the Content-Type header is a claim, not a fact, and the file extension is part of the filename the uploader chooses. A file named invoice.pdf with Content-Type: application/pdf can be a PHP script, a ZIP archive, or an HTML page carrying a script tag. If your server trusts the label, that file gets stored and eventually served somewhere it should never have reached. Type validation stops it, and it has to happen on the server, against the bytes themselves.
What the browser actually sends
When a user picks a file, the browser guesses its MIME type, usually from the extension, and sends that guess in the request. Nothing on the server can verify the guess from the header alone. Anyone can send the same request with a tool like curl and set the type to anything:
curl -F "file=@shell.php;type=image/png" https://example.com/upload
Your server receives a file called shell.php that claims to be a PNG. A validation check that reads file.mimetype or the extension passes it without a second thought. That hole is one of the first things an automated scanner tries. Extension checks and MIME checks are useful as a first filter for honest users, but they are not security controls. They reject the wrong file only when the uploader is cooperating.
Magic bytes: read the file, not the label
Most file formats begin with a fixed signature, known as magic bytes. A PNG always starts with 89 50 4E 47, a JPEG with FF D8 FF, a PDF with %PDF, a ZIP with 50 4B 03 04, and a GIF with 47 49 46 38. A file that claims to be a PNG but starts with <?php is not a PNG, whatever its name and headers say. Reading the first few bytes catches the entire class of renamed-script uploads.
const SIGNATURES = {
png: [0x89, 0x50, 0x4e, 0x47],
jpg: [0xff, 0xd8, 0xff],
pdf: [0x25, 0x50, 0x44, 0x46], // %PDF
gif: [0x47, 0x49, 0x46, 0x38],
zip: [0x50, 0x4b, 0x03, 0x04],
};
function sniffType(buffer) {
for (const [type, sig] of Object.entries(SIGNATURES)) {
if (sig.every((b, i) => buffer[i] === b)) return type;
}
return 'unknown';
}
// Accept only when extension, declared MIME, and sniffed type agree.
const actual = sniffType(headerBytes);
if (actual === 'unknown' || actual !== expectedType) {
rejectUpload('Unsupported file type');
}
Read only the first bytes you need, before the file is written anywhere permanent. The check belongs in the upload handler, not in a background job that runs after the file is already on disk — the same ordering our post on real-time scanning before storage recommends for malware scanning. A file that fails validation should never reach your storage bucket.
Why magic bytes alone are not enough
A signature check proves the file starts like the format it claims to be. It does not prove the rest of the file is that format. Polyglot files exploit this: a file can be a valid JPEG and a valid HTML page at the same time, or a GIF header followed by JavaScript. If that file is later served to a browser, the browser may sniff the content and execute the script part. A ZIP signature is another trap: Word documents, spreadsheets, and EPUBs are all ZIP archives, so a ZIP signature tells you almost nothing about what the file actually contains.
The fix is to actually decode the file. An image library that re-encodes the upload fails on a file that is not a real image, and the re-encoded output is clean by construction. A PDF parser will reject a file that is only a PDF header followed by junk. If a file cannot be decoded by a real parser for its claimed format, reject it. SVG deserves special treatment: it is XML, it can contain scripts and external references, and it should be sanitised with a dedicated SVG sanitiser or rejected outright unless your application genuinely needs it.
Serving is the other half of the defence. Even a perfectly validated file can be dangerous if the browser guesses its type wrong when it is downloaded. Serve user files with an explicit Content-Type, X-Content-Type-Options: nosniff, and Content-Disposition: attachment so downloads are saved rather than rendered in the page. The file upload security checklist covers the full serving setup, and where to store user uploads explains why uploaded files belong outside your web root, ideally in object storage on a separate domain.
A validation pipeline that holds up
Put the checks together in this order, and reject at the first failure.
- Allowlist, never blocklist: define the exact formats you accept, such as PNG, JPEG, and PDF. Reject everything else by default instead of trying to enumerate dangerous types.
- Check all three labels: extension, declared MIME type, and sniffed magic bytes must agree with each other and with the allowlist.
- Enforce size before reading: cap the upload size up front so a huge file cannot exhaust memory while you inspect it. Upload quotas and rate limits cover the size and abuse side of this.
- Decode or re-encode: pass images through a real image library and documents through a real parser. A file that fails to decode is not that file type.
- Sanitise or reject SVG: treat SVG as code, not as an image, unless you have a sanitiser in the pipeline.
- Scan after validation: type validation and malware scanning are different checks — malware scanning and quarantine covers what happens when a well-formed file is still malicious.
- Serve safely: correct
Content-Type,nosniff,Content-Disposition: attachment, and a separate domain for user content. - Log rejections: record the declared type, the sniffed type, and the uploader. A burst of mismatched types is usually a scanner probing your endpoint.
What to do when a file fails validation
Reject it without storing it anywhere first. A rejected file has no business in your storage bucket, your quarantine folder, or a temp directory that another process might pick up. Return a plain error such as “This file type is not supported”, without explaining which check caught it; the details belong in your server logs. Log the declared type, the sniffed type, the size, and the source. One rejection is usually a user mistake. Ten in a minute from one source is a probe, and it is worth an alert. With direct-to-cloud uploads with presigned URLs, the same validation still has to run on the object after upload and before the file is marked available — otherwise the direct path bypasses everything this post describes.
MIME types and extensions are conveniences for honest users, not evidence about a file. The evidence is in the first bytes, in whether the file decodes as the format it claims to be, and in how it is served afterwards. Check the bytes, decode the file, serve it safely, and most upload attacks fail at the front door. If your application accepts uploads and you are not sure what its validation actually checks, talk to us — our custom software team reviews upload pipelines for business applications and fixes the gaps before they become incidents.