Secure File Upload: Stop Malicious Uploads

By Bug Circuit Security Team
Secure File Upload: Stop Malicious Uploads

Is your own website affected? Check it free in 2 minutes.

Passive outside check only. Nothing is attacked, no signup.

To secure a file upload, accept only a short list of file types you choose, check the real content and size on the server, rename every file, store it where the web server will not run it, and block script execution in the upload folder. No single check is enough on its own. You need several layers, so one mistake does not hand an attacker a way in.

This guide is for owners and developers of sites that take uploads: contact forms with attachments, document portals, profile photos, WordPress forms. You will get a seven-step checklist, short PHP and WordPress examples you can copy, and a table that maps each step to the OWASP File Upload Cheat Sheet.

Why uploads are risky

An upload form lets a stranger put a file on your server. If that file is a script (for example a .php file) and the server runs it, the attacker now controls part of your site. That script is called a web shell: a small backdoor page that lets someone run commands through their browser.

OWASP lists this weakness as Unrestricted File Upload. It does not need a clever exploit. It only needs a form that trusts what it receives.

The good news: the fixes are well known and mostly cheap. Here is the order to apply them in.

The seven-step secure file upload checklist

1. Decide which file types you actually need

Write down the types you truly need. A job application form may need PDF and DOCX. A profile photo form needs JPG and PNG. Nothing else.

Use an allowlist (a list of what is permitted), never a blocklist of "bad" types. Blocklists miss things like .phtml, .phar or odd capitalization such as .PhP. OWASP recommends allowing only the extensions that are critical to the business.

Be careful with SVG images. An SVG is an XML file that can contain scripts. Skip it unless you sanitize it.

2. Check the real file type on the server

Browser checks are for convenience only. An attacker can skip your page and send the request directly. The Content-Type and filename that arrive with the file are also chosen by the sender, so you cannot trust them.

On the server, check the extension against your allowlist, then check the file's actual content (its "magic bytes", the first few bytes that identify a format). In PHP, the finfo class does this.

3. Limit file size

Set a limit that fits your use case, such as 5 MB. This stops people from filling your disk or slowing your site with huge files. Set it in two places: your code, and the server settings.

For PHP, these php.ini settings cap uploads (see the PHP manual on upload settings):

upload_max_filesize = 5M
post_max_size = 6M
max_file_uploads = 3

4. Rename every file

Never store a file under the name the user gave it. Names like shell.php.jpg, ../../index.php or very long names can cause trouble. Generate a random name and add a safe extension that you picked yourself, based on the checked type. OWASP calls this changing the filename and recommends a generated one.

Keep the original name in your database if you need to show it to users. Never use it as a path.

5. Store files outside the web root

The web root is the folder your web server serves directly to visitors. If an uploaded file sits inside it, anyone can request it by URL, and the server may run it. Store uploads in a folder above the web root, such as /var/app-uploads/, which has no public URL.

When users need to download a file, serve it through a small script that checks who is asking and sends the file with safe headers. The PHP example below shows this.

6. Block script execution in the upload folder

Sometimes files must live inside the web root. WordPress is the common case: it saves media in wp-content/uploads/. In that case, tell the server never to run scripts there. This is your safety net if a bad file slips through.

The rules below match a script extension anywhere in the filename, followed by a dot or the end of the name. That also catches double extensions like shell.php.jpg, which can still run on some Apache setups that use AddHandler.

Apache (put this in wp-content/uploads/.htaccess, if your host allows .htaccess overrides):

<FilesMatch "(?i)\.(php|phtml|phar|php[0-9]|pl|py|cgi|sh)(\.|$)">
  Require all denied
</FilesMatch>

Nginx (in your server block, using the path to your uploads):

location ^~ /wp-content/uploads/ {
    location ~* \.(php|phtml|phar|php[0-9]|pl|py|cgi|sh)(\.|$) { return 403; }
}

Reload the web server after changing Nginx. Test it in a staging copy: copy a harmless text file named test.php into wp-content/uploads/ using SFTP or your host's file manager (not through the media library, which rejects .php), then request its URL and confirm you get 403, not a page or output. Delete it afterwards.

7. Add safe download headers, permissions and scanning

When you serve user files, send X-Content-Type-Options: nosniff so browsers do not guess a type. Use Content-Disposition: attachment for documents so they download instead of opening in the page. Check your download script's headers with curl -I against a file URL, for example curl -I 'https://example.com/download.php?id=123'. The free security headers tool checks a page's response headers, so it helps for your site's pages but does not check what your download script sends.

Also keep file permissions tight (the web server user should read uploads but not execute them). If you accept documents from the public, scan them with an antivirus such as ClamAV, for example clamscan --infected --recursive /var/app-uploads. Finally, only let people upload who need to. Require a login where you can.

Secure file upload in PHP: a short example

This handler applies steps 2 to 5. It is a starting point, not a complete app. Add login checks and CSRF protection (a token that proves the form came from your own page) where your site needs them.

<?php
declare(strict_types=1);

$maxBytes = 5 * 1024 * 1024;
$allowed  = [
    'image/jpeg'      => 'jpg',
    'image/png'       => 'png',
    'application/pdf' => 'pdf',
];

if (!isset($_FILES['upload']) || $_FILES['upload']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    exit('Upload failed.');
}

$file = $_FILES['upload'];

if ($file['size'] > $maxBytes || !is_uploaded_file($file['tmp_name'])) {
    http_response_code(400);
    exit('File too large or invalid.');
}

// Check real content, not the name or browser-sent type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime  = $finfo->file($file['tmp_name']);

if (!isset($allowed[$mime])) {
    http_response_code(415);
    exit('File type not allowed.');
}

// Random name, extension chosen by us
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
$dest = '/var/app-uploads/' . $name; // outside the web root

if (!move_uploaded_file($file['tmp_name'], $dest)) {
    http_response_code(500);
    exit('Could not save file.');
}
chmod($dest, 0640);

For images, you can go one step further and re-encode them with the GD library (open the image and save a fresh copy). This drops hidden data tucked inside a file. OWASP calls this idea Content Disarm and Reconstruction (CDR).

To serve a stored file safely, use a separate script that looks up the file by its random name after checking permissions, then sends it:

header('Content-Type: application/octet-stream');
header('X-Content-Type-Options: nosniff');
header('Content-Disposition: attachment; filename="document"');
readfile('/var/app-uploads/' . basename($storedName));

WordPress file upload security

WordPress already blocks PHP files in its media library through a list of allowed types. Your risk usually comes from plugins and from loosening that list.

  • Limit types on a form. In Contact Form 7, set the file field like this: [file your-file limit:5mb filetypes:jpg|jpeg|png|pdf].
  • Restrict the media library. Add this to a small custom plugin or your child theme's functions.php:
add_filter('upload_mimes', function ($mimes) {
    return [
        'jpg|jpeg|jpe' => 'image/jpeg',
        'png'          => 'image/png',
        'pdf'          => 'application/pdf',
    ];
});

This replaces WordPress's default list, so add any other types you need (for example gif, webp) or media uploads for those will stop working.

  • Handling your own upload code? Use wp_handle_upload() with a mimes override rather than move_uploaded_file(), so WordPress runs its own type checks. See the WordPress developer reference.
  • Never enable uploads of extra types such as SVG or ZIP through a plugin unless you trust that plugin and keep it updated.
  • Block PHP in wp-content/uploads/ with the Apache or Nginx rules from step 6.
  • Remove upload plugins you do not use. Old file-manager and form plugins are a common way in.

How each step maps to OWASP

StepWhat it stopsOWASP File Upload Cheat Sheet idea
Allowlist of typesScript and unexpected filesList allowed extensions
Check real contentFake extensions and spoofed typesValidate file type, do not trust Content-Type
Size limitDisk filling, slow siteSet a file size limit
Rename filesPath tricks, overwriting, double extensionsChange the filename
Store outside web rootDirect access and executionStore files on a different path or server
Block execution in folderA missed web shell runningSet safe permissions, no execution
Headers, scan, loginBrowser sniffing, malware, anonymous abuseAntivirus, authorized users only

OWASP also covers this in its Web Security Testing Guide on file upload testing, which shows what a tester tries against an upload form.

How to check your own upload forms

Try these in a staging copy, or with permission on your own site:

  1. Upload a plain text file renamed to .php. It should be rejected.
  2. Upload a real PDF renamed to .jpg. It should be rejected or stored under a safe name.
  3. Upload a file just over your size limit. It should fail cleanly.
  4. Check the stored name. It should be random, not the original.
  5. Request an uploaded file's URL. It should download or return nothing, never run.
  6. Check your download script's headers with curl -I against a file URL, for example curl -I 'https://example.com/download.php?id=123'. Look for X-Content-Type-Options: nosniff and Content-Disposition: attachment.

If you want a quick outside look first, the free website security check reviews your domain passively. For a wider view of what attackers can reach, read is my website hackable. If you already suspect a planted file, go to what to do when your website is hacked.

Key takeaways

  • Allow only the few file types you need, checked on the server by real content, not by name or browser-sent type.
  • Limit size, and rename every file to a random name with an extension you choose.
  • Store uploads outside the web root, or block script execution in the upload folder if they must stay inside.
  • In WordPress, restrict allowed types, avoid SVG and ZIP uploads, and remove unused upload plugins.
  • Test your form with a fake .php file, and follow the OWASP File Upload Cheat Sheet for anything beyond the basics.

What to do next

These steps cover the common mistakes, but every site wires uploads differently. A person testing your form by hand will find gaps a checklist misses, such as an old plugin or a forgotten endpoint. A Bug Circuit audit is a manual test of one website by a real engineer, ending in a written report with evidence and fix steps. The Essential plan is $49 one-time. It covers 1 website, with 3 manual audits you can request within one month. Fixing is separate: we send a price first, and you pay only if you agree. It is not a compliance certification, and it does not replace secure coding on your side.

Want certainty, not guesswork?

A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.

See pricing

Frequently asked questions

How to secure file upload?
Allow only the file types you need, check the real file content and size on the server, and rename every file to a random name. Store files outside the web root, or block script execution in the upload folder. Add a login requirement and antivirus scanning where it makes sense.
What are secure file upload best practices?
Use an extension allowlist, validate content rather than trusting the browser-sent type, limit file size, and generate new filenames. Keep uploads out of the web root and stop the server from running scripts in the upload folder. The OWASP File Upload Cheat Sheet lists these and more.
How do I do a secure file upload in PHP?
Check `$_FILES['upload']['error']` and size, detect the type with `finfo`, and compare it to an allowlist. Save the file with `move_uploaded_file()` under a random name, in a folder outside the web root. Serve downloads through a script that sets `X-Content-Type-Options: nosniff`.
Is checking the file extension enough to stop malicious uploads?
No. Extensions are easy to fake, and attackers use tricks like double extensions or odd capitalization. Check the real content on the server, rename the file, and block script execution in the folder where files are stored.
Can a WordPress upload plugin let hackers in?
It can, if the plugin allows risky file types or has a known flaw. Keep plugins updated, remove ones you do not use, and limit allowed types. Blocking PHP execution in `wp-content/uploads/` adds a useful safety net.

Keep reading

See what attackers see, for free

Run the free passive check on your website. No login, no impact on your site, results in seconds.

Ready for the full manual audit? See pricing

Published by Bug Circuit. Written with AI assistance and reviewed for accuracy before publishing.