December 2, 2026
The PHP File-Upload Mistakes That Turn an Upload Form Into a Remote Shell
Why $_FILES[‘type’] and the file extension can’t secure an upload — and the content-based checks that actually stop a PHP shell.

By Ann R.
12 min read
- 1 1. Never trust the client-supplied MIME type ($_FILES['type'])
- 2 2. The filename and extension are attacker-controlled too
- 3 3. The reliable check: detect the type from the file's contents
- 4 4. Check $_FILES['error'] first — a present file can be a failed upload
- 5 5. Verify it's a genuine upload with is_uploaded_file
A file upload is one of the most dangerous features you can add to a web application, and one of the easiest to get subtly wrong. The failure mode is severe: a validation that looks thorough — checks the type, checks the extension, stores the file — can still let an attacker upload a PHP script and then execute it, turning your innocent "upload your profile picture" form into a remote shell on your server. The gap is that almost every check developers reach for first validates something the attacker controls: the filename, the extension, the client-supplied MIME type. None of those are the real type of the file, and treating them as if they were is exactly how upload handlers get compromised.
This is a tour of the file-upload mistakes that cause real breaches, each demonstrated on PHP 8.3 with real output — including a file named shell.png that is actually PHP, a valid image that also contains executable PHP, and the content-based check that catches the first (and why even that isn't enough for the second). File uploads are a place where a plausible-looking validation and a secure one look almost identical in the code, so knowing which checks are real and which are theater is the whole game.
1. Never trust the client-supplied MIME type ($_FILES['type'])
Start with the check that feels right and protects nothing. $_FILES['userfile']['type'] — the MIME type PHP gives you for an uploaded file — comes directly from the Content-Type header the client sent with the upload. It is not detected by the server; it's whatever the uploading client claimed. So an attacker uploading evil.php simply sets the Content-Type header to image/png, and $_FILES['type'] reads image/png for a PHP file.
This means a check like if ($_FILES['userfile']['type'] === 'image/png') passes a PHP script the moment the attacker lies about the type — which they trivially can, since they control the entire request. The $_FILES['type'] value is useful for exactly nothing security-related; it's attacker-controlled input wearing the costume of a server-verified fact. The rule is absolute: never validate an upload by $_FILES['type']. It's one of the most common upload-security mistakes precisely because it looks like a legitimate MIME-type check and reads naturally in code, but it's checking the attacker's claim about their own file. The real type has to be determined by the server, from the file's contents — which is point 3. Any upload validation built on $_FILES['type'] is validating a value the attacker filled in.
2. The filename and extension are attacker-controlled too
The second instinct — check the file extension — fails for the same root reason: the filename comes from the client, so the extension is whatever the attacker named their file. Verified:
// an attacker uploads a PHP file but names it shell.png
file_put_contents('shell.png', "<?php echo 'i am php, not a png'; ?>");
pathinfo('shell.png', PATHINFO_EXTENSION); // "png" — but the content is PHP// an attacker uploads a PHP file but names it shell.png
file_put_contents('shell.png', "<?php echo 'i am php, not a png'; ?>");
pathinfo('shell.png', PATHINFO_EXTENSION); // "png" — but the content is PHPVerified: a file containing PHP, named shell.png, reports its extension as png — the name says image, the content is code. An extension check (if ($ext === 'png')) passes this file. And extension-based checks have a whole family of bypasses beyond the basic lie. Verified:
pathinfo('shell.php.png', PATHINFO_EXTENSION); // "png" — double extension
pathinfo('shell.png.php', PATHINFO_EXTENSION); // "php" — the dangerous order
pathinfo('shell.pHp', PATHINFO_EXTENSION); // "pHp" — mixed casepathinfo('shell.php.png', PATHINFO_EXTENSION); // "png" — double extension
pathinfo('shell.png.php', PATHINFO_EXTENSION); // "php" — the dangerous order
pathinfo('shell.pHp', PATHINFO_EXTENSION); // "pHp" — mixed caseVerified: the double extension shell.php.png reports png (and some misconfigured servers execute it as PHP anyway, based on the first extension), shell.png.php reports php, and shell.pHp uses mixed case that a case-sensitive blocklist misses. Extension checks are a minefield of bypasses: double extensions that different layers interpret differently, case variations, trailing dots and spaces, null bytes (historically), and alternate executable extensions (.phtml, .php5, .phar). The deeper problem is the same as point 1 — the extension is part of the client-supplied filename, so it's attacker-controlled and tells you nothing reliable about what the file actually is. Checking it is checking the attacker's label on their own package.
3. The reliable check: detect the type from the file's contents
Since the name and the client's claim are both untrustworthy, the real type must be read from the file's bytes — its "magic numbers," the signature bytes at the start of a file that identify its format. PHP's finfo (fileinfo) does this. Verified against the fake shell.png:
$finfo = new finfo(FILEINFO_MIME_TYPE);
$finfo->file('shell.png'); // "text/x-php" — detected the REAL type from content
$finfo->file('ok.png'); // "image/png" — a genuine PNG reads as image/png$finfo = new finfo(FILEINFO_MIME_TYPE);
$finfo->file('shell.png'); // "text/x-php" — detected the REAL type from content
$finfo->file('ok.png'); // "image/png" — a genuine PNG reads as image/pngVerified: finfo inspected the contents of shell.png and reported text/x-php — seeing through the fake .png name to the actual PHP inside — while a genuinely valid PNG correctly read as image/png. This is the difference between a real type check and theater: finfo reads the file's actual bytes, so it can't be fooled by a renamed file or a spoofed Content-Type header. The correct validation is to detect the MIME type with finfo from the uploaded temp file's content, and accept only an allowlist of types you actually want — image/png, image/jpeg, whatever your feature needs — rejecting everything else. Crucially, you then map that detected type to an extension you choose, rather than keeping the user's. So the flow is: finfo tells you it's genuinely image/png, and you decide the file gets a .png extension and a name you generate. Content-based detection via finfo is the one type check that actually resists the attacker, because it examines what they can't fake without changing the file into a real file of that type — which leads to the one case where even this isn't sufficient (point 8).
4. Check $_FILES['error'] first — a present file can be a failed upload
Before any type checking, there's a correctness check people skip: the upload's error code. A file entry can exist in $_FILES while the upload actually failed — too big, partially transferred, or no file at all — and proceeding on the file's mere presence processes a broken or empty upload. Verified behavior aside, the error codes:
// UPLOAD_ERR_OK = 0, INI_SIZE = 1, PARTIAL = 3, NO_FILE = 4
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
// reject — the upload didn't actually succeed
}// UPLOAD_ERR_OK = 0, INI_SIZE = 1, PARTIAL = 3, NO_FILE = 4
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
// reject — the upload didn't actually succeed
}Verified: the upload error constants are UPLOAD_ERR_OK (0), UPLOAD_ERR_INI_SIZE (1, exceeded the size limit), UPLOAD_ERR_PARTIAL (3, interrupted), and UPLOAD_ERR_NO_FILE (4, nothing sent). The mistake is checking if (isset($_FILES['userfile'])) and proceeding — because a file can be present with an error other than zero, and then its temp file is truncated, empty, or absent. The first line of any upload handler should be if ($file['error'] !== UPLOAD_ERR_OK) reject(), because every subsequent check (reading the content, detecting the type) assumes a complete, successful upload. This isn't a security check so much as a correctness one, but it's the foundation the security checks stand on: you can't meaningfully validate the type of a file that didn't fully arrive. Checking the error code first means the rest of your validation operates on a real, complete file.
5. Verify it's a genuine upload with is_uploaded_file
A subtle but important guard: confirm the file you're about to process was actually uploaded via HTTP, not a path an attacker managed to slip into your processing. is_uploaded_file() returns true only for a file that came through a POST upload in this request, which prevents an attacker from tricking your code into treating an existing server file (via some other injection) as if it were their upload:
if (!is_uploaded_file($file['tmp_name'])) {
// reject — this isn't a real HTTP upload
}
// and when storing it, use move_uploaded_file (not rename/copy),
// which also checks is_uploaded_file internally:
move_uploaded_file($file['tmp_name'], $destination);if (!is_uploaded_file($file['tmp_name'])) {
// reject — this isn't a real HTTP upload
}
// and when storing it, use move_uploaded_file (not rename/copy),
// which also checks is_uploaded_file internally:
move_uploaded_file($file['tmp_name'], $destination);The reasoning is defense against a specific attack: if an attacker can influence the tmp_name your code reads (through a separate vulnerability), is_uploaded_file ensures you only process files PHP itself registered as uploads in this request. And move_uploaded_file — the correct function for storing an upload — performs the same check internally, refusing to move anything that wasn't a genuine upload. The mistake is using rename() or copy() to store an upload (bypassing that safety check) or reading tmp_name without confirming it's a real upload. The pattern is to validate with is_uploaded_file and store with move_uploaded_file, so both the check and the move verify the file's provenance. It's a small guard, but it closes the gap where a path-manipulation bug elsewhere could turn your upload handler into an arbitrary-file reader.
6. Never store the file under the client's name — generate your own
Here's a mistake that combines a correctness problem with a security one: storing the uploaded file using the name the client provided. The client's filename is attacker-controlled (point 2), so using it as part of a storage path invites path traversal — a filename like ../../var/www/html/shell.php tries to escape your upload directory and land the file somewhere dangerous. Verified:
$clientName = "../../var/www/html/shell.php";
basename($clientName); // "shell.php" — strips the directory part$clientName = "../../var/www/html/shell.php";
basename($clientName); // "shell.php" — strips the directory partVerified: basename strips the directory components from the malicious path, leaving shell.php. But — and this is critical — basename is a string function, not a security control; it happens to strip ../ here, but relying on it for upload safety is fragile, and it still leaves you storing a file the attacker named shell.php (an executable extension) in your uploads directory. The robust answer isn't to sanitize the client's filename; it's to discard it entirely and generate your own:
$safeName = bin2hex(random_bytes(16)) . '.' . $allowedExtensionForDetectedType;
// store as e.g. "a3f9...c21.png" — a name YOU control, with an extension YOU chose$safeName = bin2hex(random_bytes(16)) . '.' . $allowedExtensionForDetectedType;
// store as e.g. "a3f9...c21.png" — a name YOU control, with an extension YOU choseGenerating your own filename — a random name plus the extension you derived from the content-detected type — eliminates the entire class of filename-based attacks at once: no path traversal (the name has no path), no executable extension (you chose the extension), no overwriting other files (the random name won't collide), no encoding tricks (there's nothing user-controlled left in the name). You can store the original name separately in the database for display, but the file on disk should bear a name you generated. This single practice — never use the client's filename for the stored file — closes path traversal, extension attacks, and overwrite attacks in one move.
7. Store uploads outside the web root — or disable execution there
Even with perfect type validation, there's a defense-in-depth layer that matters enormously: where the file lives, and whether it can be executed. If an uploaded file is stored in a directory that's reachable by URL and the web server will execute PHP there, then any malicious file that slips through your validation (and point 8 shows how one can) becomes executable by simply requesting its URL. The defenses, in order of preference:
The best option is to store uploads outside the web root entirely, so there's no URL that maps to the file at all — it can only be reached through a PHP script you control, which reads the file and serves it with the right headers. The second option, when files must be web-accessible, is to disable PHP execution in the upload directory (web-server configuration that removes the PHP handler there), so even a PHP file sitting in the directory is served as a download, not run. The mistake is the default: dropping uploads into a directory under the web root with normal execution enabled, so a file named x.php that got through validation runs when requested. The principle is that type validation is your first line, but execution prevention is the line that saves you when validation is bypassed — and validation can be bypassed, as the polyglot case shows. Assume a malicious file might reach disk, and make sure it can't be executed when it does. Uploads outside the web root, served through a controlled script, is the configuration that holds even when everything upstream fails.
8. The polyglot problem: a valid image that is also PHP
This is the case that proves type validation alone isn't enough, and it's unsettling. A file can be a genuinely valid image — passing finfo, passing getimagesize — and simultaneously contain executable PHP appended to it. Verified:
// valid PNG bytes, then PHP appended
file_put_contents('polyglot.png', $validPngBytes . "\n<?php echo 'PWNED'; ?>");
(new finfo(FILEINFO_MIME_TYPE))->file('polyglot.png'); // "image/png" — passes!
getimagesize('polyglot.png'); // valid image — passes!// valid PNG bytes, then PHP appended
file_put_contents('polyglot.png', $validPngBytes . "\n<?php echo 'PWNED'; ?>");
(new finfo(FILEINFO_MIME_TYPE))->file('polyglot.png'); // "image/png" — passes!
getimagesize('polyglot.png'); // valid image — passes!Verified: a file with valid PNG bytes followed by PHP code was detected as image/png by finfo and recognized as a valid image by getimagesize — passing both content-based checks — while still carrying executable PHP in its tail. This works because image formats tolerate trailing data: the image is valid up to its end marker, and the appended PHP is just ignored as an image but executed if the file is ever run through the PHP interpreter. So content-based type validation, while necessary and far better than name/MIME checks, is not sufficient on its own — a determined attacker produces a file that is both a real image and a real script. This is exactly why point 7's execution prevention matters: the polyglot passes every type check, so the thing that saves you is that the file can't be executed where it's stored. The complementary defense is to re-encode uploaded images: load the image and re-save it (via GD or Imagick), which reconstructs the image from its pixels and discards anything appended, stripping the PHP payload entirely. Type validation catches the obvious attacks; re-encoding plus execution prevention catches the polyglot that type validation can't.
9. Enforce a size limit — at every layer
A denial-of-service angle that's easy to forget: without a size limit, a user can upload a file large enough to exhaust disk space or memory, and a naive handler that reads the whole file into memory makes it worse. Size limits need enforcing at multiple layers because each can be bypassed or misconfigured:
PHP has upload_max_filesize and post_max_size (ini settings that cap upload and total POST size), and these are your backstop — but note that post_max_size being exceeded can produce an empty $_FILES with surprising behavior, so handle that case. The web server has its own limit (nginx client_max_body_size, Apache LimitRequestBody) that should be set consistently. And your application should check $_FILES['userfile']['size'] against your feature's actual limit — a profile picture doesn't need to allow 2GB. The mistake is relying on a single layer, or none: no limit means a resource-exhaustion vector, and an inconsistent limit between the web server and PHP produces confusing failures (the web server rejects before PHP sees it, or vice versa). Set a sensible limit at the web-server layer, the PHP ini layer, and the application layer, all consistent, so a large upload is rejected cleanly and early rather than consuming resources or producing a baffling error. The limit is both a security control (against resource exhaustion) and a UX one (a clear "file too large" beats a mysterious failure).
10. The complete safe-upload checklist
Pulling it into the sequence a secure upload handler actually follows, in order:
First, check the error code — $file['error'] === UPLOAD_ERR_OK or reject; nothing else is meaningful on a failed upload. Second, check the size against your application limit. Third, verify it's a real upload with is_uploaded_file($file['tmp_name']). Fourth, detect the real type from content with finfo and accept only an allowlist of MIME types — never $_FILES['type'], never the extension. Fifth, generate your own filename — a random name plus the extension you derived from the detected type, discarding the client's name entirely. Sixth, store it with move_uploaded_file into a directory outside the web root (or one where execution is disabled). Seventh, for images, re-encode them to strip any polyglot payload. And underlying all of it: execution prevention on the storage location, so a file that somehow passes everything still can't run.
The anti-checklist — the mistakes — maps directly onto skipping any of these: trusting $_FILES['type'] (attacker-controlled), checking the extension (attacker-controlled), using the client's filename (traversal and executable extensions), skipping the error-code check (processing broken uploads), storing in an executable web-root directory (a passed-through file runs), and assuming type validation alone is enough (the polyglot defeats it). Each mistake is a plausible-looking check that validates something the attacker controls, or a missing layer that would have contained the damage. Secure file upload is less about one clever check than about this sequence of them, because each closes a different bypass, and the attacker only needs one gap.
The thread through all ten
Step back and almost every file-upload vulnerability comes from the same root: trusting attacker-controlled metadata about the file instead of the file's actual content, and failing to contain a malicious file that gets through. The filename, the extension, the Content-Type header — all are supplied by the uploader and tell you nothing reliable. The real type lives in the file's bytes, which is why finfo content detection is the only trustworthy type check; and even that can be fooled by a polyglot, which is why execution prevention and re-encoding exist as the layers that contain what validation misses. Every mistake in the list is either trusting something the attacker filled in, or omitting a containment layer that would have made a bypass harmless.
The habit worth building is to treat an uploaded file as hostile until proven otherwise, and to defend in layers rather than trusting any single check. Detect the type from content, not the name. Generate your own filename, never the client's. Store outside the web root, or disable execution where you store. Re-encode images. Check the error code and the size. No single one of these is sufficient — content detection is beaten by the polyglot, execution prevention is moot if you also leak the file through a path bug, a size limit doesn't stop a malicious small file — but together they mean an attacker has to defeat every layer, and a profile-picture form stops being a remote-shell delivery mechanism. The upload handler that checks the extension and calls it secure is the one in the breach report; the one that validates content, generates its own names, and can't execute what it stores is the one that holds.
Which did you ship before you knew better — the handler that trusted $_FILES['type'], or the one that stored uploads under the web root with the client's own filename? The $_FILES['type'] one is nearly universal in older code, and it's the check that looks most like real security while providing exactly none.