Key points
- Check a file’s type from its content with
finfo, never from its extension or the browser-sent type. - Rename every file to a random identifier and keep it outside the public folder.
- Serve downloads through a script that checks permissions and sets strict headers.
Job applications, a customer area for supporting documents, avatars: file uploads are quick to build and rarely reviewed afterwards. When we take over existing projects, they are among the things we fix most often. The usual story is a file called invoice.php dropped into /uploads/ and then simply requested in a browser. Here is how we handle uploads on our PHP projects.
Trust the content, not the label
Both $_FILES['doc']['name'] and $_FILES['doc']['type'] come from the browser, so the user controls them. The only thing you can rely on is the temporary file itself, which the fileinfo extension inspects. Compare the result to a short allow-list and let that list pick the final extension.
function handleUpload(array $file, string $storageDir): array
{
if (!isset($file['error']) || is_array($file['error'])) {
throw new RuntimeException('Invalid request.');
}
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException(match ($file['error']) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'File too large.',
UPLOAD_ERR_NO_FILE => 'No file sent.',
default => 'Upload failed.',
});
}
if ($file['size'] > 5 * 1024 * 1024) {
throw new RuntimeException('File too large (5 MB max).');
}
$allowed = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
'application/pdf' => 'pdf',
];
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
$ext = $allowed[$mime] ?? throw new RuntimeException('File type not allowed.');
$storedName = bin2hex(random_bytes(16)) . '.' . $ext;
if (!move_uploaded_file($file['tmp_name'], $storageDir . '/' . $storedName)) {
throw new RuntimeException('Could not save the file.');
}
return ['stored' => $storedName, 'mime' => $mime, 'original' => $file['name']];
}
A random stored name means no odd characters, no collisions and no ../ sneaking in. Keep the original name in the database for display only.
Resist adding SVG because “it’s an image”: it is XML and can carry JavaScript. If you must accept it, run it through a dedicated sanitiser or never serve it from your own domain.
Keep files out of the web root
The simplest protection is making sure the web server cannot serve the file at all. Store uploads one level above the document root, for instance /var/www/app/storage/ when the site is served from /var/www/app/public/.
If your host forces a public folder, at least block script execution inside it:
# uploads/.htaccess (Apache) : never execute anything stored here
<FilesMatch ".(phpd?|phtml|phar)$">
Require all denied
</FilesMatch>
Nginx ignores .htaccess, so on Nginx the equivalent rule belongs in the server config. We have seen this protection vanish quietly after a hosting move more than once.
Serve downloads through a permission check
A document uploaded by a customer should only be readable by that customer and your team. The download link therefore points to a script that loads the record filtered by the logged-in user:
$doc = $documents->findForUser((int) ($_GET['id'] ?? 0), $currentUser);
if ($doc === null) {
http_response_code(404);
exit;
}
$path = STORAGE_DIR . '/' . $doc->storedName;
header('Content-Type: ' . $doc->mime);
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($doc->originalName));
readfile($path);
nosniff stops the browser from guessing a different type, and attachment forces a download instead of rendering the file on your domain.
Settings that fail silently
When a request exceeds post_max_size, PHP empties $_POST and $_FILES entirely. No error, just a form that looks like it was submitted blank. We always test with a file above the limit to make sure users get a clear message.
For photos, re-encoding with GD or Imagick (while resizing anyway) also strips EXIF metadata, which can include the GPS location where the picture was taken.
FAQ
Isn’t checking the extension enough?
No. The user picks the extension. A file called photo.jpg can contain anything; only inspecting the content tells you what it really is.
Should uploaded files be virus-scanned?
For documents your team will open on their own machines, such as CVs or attachments, scanning with a tool like ClamAV is a sensible extra layer. It doesn’t replace the checks above.
Does your site or app accept files and you’re not sure how they’re handled? We review and harden upload flows on PHP and WordPress projects.



