📤
Security

Securing a File Upload Form: Validation, Storage and Delivery

23.11.2026
← All articles

An upload form is one of the riskiest parts of any website. A normal form accepts text; an upload form brings an entire file onto your server, whether it is an image, a document or a disguised program. A company site collecting CVs, a clinic portal where patients send lab results and a school platform for homework all face the same question: how far can you trust a file sent by a stranger? The right answer is not at all, and to check every step separately.

Mistakes that invite attacks

The most common mistake is a blacklist of extensions: .php and .exe are blocked, but .phtml, .phar or .PhP slip through. The second is trusting $_FILES['type'], which the attacker controls and can set to image/jpeg for anything. The third is keeping the user-supplied file name, where something like ../../index.php or a duplicate name can overwrite other files. Add a public folder with PHP execution enabled and no size limit, and one bad file is enough to run code or fill the disk.

Core rules

  1. Allowlist only the extensions you need, such as jpg, png, pdf.
  2. Check the real type with finfo and require it to match the extension.
  3. Limit size in code and in PHP settings (upload_max_filesize, post_max_size).
  4. Rename files to random names; store the original name in the database if needed.
  5. Store outside the web root or in a folder where PHP is disabled.

A practical PHP example

This code applies all of the rules: it checks the upload error, size, extension and actual content type, then moves the file under a random name into a private folder. move_uploaded_file only moves files that really arrived over HTTP, which is an extra safeguard:

<?php
$allowed = [
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png'  => 'image/png',
    'pdf'  => 'application/pdf',
];
$maxSize = 5 * 1024 * 1024; // 5 MB

$f = $_FILES['document'] ?? null;
if (!$f || $f['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400); exit('Upload failed');
}
if ($f['size'] > $maxSize) {
    http_response_code(413); exit('File too large');
}

$ext  = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
if (!isset($allowed[$ext]) || $allowed[$ext] !== $mime) {
    http_response_code(415); exit('File type not allowed');
}

$name = bin2hex(random_bytes(16)) . '.' . $ext;
$dir  = '/var/www/example/private_uploads/'; // outside the web root
if (!move_uploaded_file($f['tmp_name'], $dir . $name)) {
    http_response_code(500); exit('Could not save file');
}

Checking extension and MIME type together matters. Check only one and either photo.php with a genuine JPEG header or a PHP script named photo.jpg gets through; requiring both to agree closes both doors.

Re-encode images

Even a real image can carry hidden data, such as code appended to the file or GPS coordinates in EXIF. Opening it with GD or Imagick and saving it again keeps only the pixels:

<?php
// Re-encode the image: metadata and anything appended to it are dropped
$src = imagecreatefromjpeg($dir . $name);
if ($src === false) { unlink($dir . $name); exit('Invalid image'); }
imagejpeg($src, $dir . $name, 85);

Risky formats: SVG, HTML and archives

SVG is XML and can contain JavaScript; served from your own domain, that script runs in the user's session. Do not accept SVG from visitors, or serve it only as a download, and treat HTML the same way. ZIP files bring a different problem: a tiny archive can expand to gigabytes, and entries containing ../ can be written outside the target folder. If you must extract, cap total size and file count and validate every name.

Serving files back

Files outside the public folder are delivered by a script, which is also where you check that the user may see them. X-Content-Type-Options: nosniff stops the browser from guessing the type, and Content-Disposition: attachment forces a download instead of rendering:

<?php
// download.php?id=42 : only the owner may fetch the file
$file = $db->fetchFileForUser((int)$_GET['id'], $currentUserId);
if (!$file) { http_response_code(404); exit; }

header('Content-Type: ' . $file['mime']);
header('X-Content-Type-Options: nosniff');
header('Content-Disposition: attachment; filename="document.' . $file['ext'] . '"');
readfile('/var/www/example/private_uploads/' . $file['stored_name']);

Example: a private clinic in Samarkand

Patients upload earlier lab results as PDFs or photos. In the first version, files landed in /uploads/ under their original names, so anyone guessing a URL could open another patient's document, and no type check existed. The rebuilt form accepts only PDF, JPG and PNG, checks MIME type with finfo, caps size at 10 MB and stores files with random names outside the web root. Doctors open them only after logging in, from the relevant patient record.

Protect the form itself

Add a CSRF token so other sites cannot submit files on a user's behalf, rate-limit anonymous uploads per IP, and scan files with antivirus if other people will see them. On sayt.uz hosting, PHP upload limits can be adjusted in the ISPmanager panel opened from your cabinet, or through support.

Related articles

🌐 The danger of misconfigured CORS: how to open your API correctly 🔍 Scanning a Website with ClamAV: Setup, Commands and Reading the Results 🦠 Malware on Your PC Steals FTP Passwords: Signs and Protection ✅ Django Security Checklist: What to Verify Before Going to Production
🌐 Language
🇺🇿 O⁠'zbek 🇺🇿 Özbek (yangi) 🇺🇿 Ўзбек 🇷🇺 Русский 🇬🇧 English ✓