Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 147 ยท PHP and the Web

File Uploads

Handle file uploads in PHP safely - multipart forms, the $_FILES array, UPLOAD_ERR codes, size and type checks with finfo, safe file names and storage outside the web root.

Profile pictures, invoices, CSV imports, attachments: sooner or later every application accepts files from its users. PHP makes receiving an upload easy. It parses the request, saves each file to a temporary location and describes it in the $_FILES superglobal. Your job is to check the result, decide whether the file is acceptable, and move it somewhere permanent.

That second part is where most security problems in PHP applications have historically come from. An upload form that trusts the file name or the browser's claimed type can let an attacker upload shell.php into a public folder and then run it by visiting its URL, taking over the whole server. This lesson shows how uploads work and how to handle them safely: checking error codes, enforcing size limits, detecting the real file type with finfo, generating safe names and storing files outside the web root.

Our editor can't receive a real upload, so the runnable examples simulate one: they create a file in the temporary folder and fill $_FILES the way PHP would. The validation code is the same you'd use on a server; the one function that refuses to work in a simulation (move_uploaded_file()) is explained along the way.

The upload form

A file upload needs a form with method="post" and enctype="multipart/form-data". Without that encoding, the browser sends only the file's name, not its contents.

HTML
<form action="/avatar.php" method="post" enctype="multipart/form-data">
  <label for="avatar">Profile picture (PNG, JPEG or WebP, max 2 MB)</label>
  <input id="avatar" name="avatar" type="file" accept="image/png,image/jpeg,image/webp">

  <label for="docs">Documents</label>
  <input id="docs" name="docs[]" type="file" multiple>

  <button>Upload</button>
</form>

The accept attribute only filters the file picker in the browser; it's a hint for users, not a check. The multiple attribute together with a name ending in [] lets the user pick several files for one field. See the HTML forms lesson for the HTML side.

What PHP puts in $_FILES

For each file field, $_FILES holds an array with six keys:

Key Example Trust it?
name holiday photo.JPG No: chosen by the client
full_path photos/holiday photo.JPG No: the relative path when a folder is uploaded (PHP 8.1+)
type image/jpeg No: the browser's guess, or anything an attacker sends
tmp_name /tmp/phpA1b2C3 Yes: where PHP stored the file
error 0 Yes: one of the UPLOAD_ERR_* constants
size 183244 Yes: the size in bytes PHP received

The temporary file is deleted automatically when the request ends, so you must move it during the request if you want to keep it. The error key is the first thing to check:

PHP Reading $_FILES and upload error codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The constants have fixed values: UPLOAD_ERR_OK is 0, INI_SIZE 1, FORM_SIZE 2, PARTIAL 3, NO_FILE 4, NO_TMP_DIR 6, CANT_WRITE 7 and EXTENSION 8. When a file input is left empty, the browser still sends the field, so you get UPLOAD_ERR_NO_FILE rather than a missing key. Check it first if the upload is optional.

Size limits in php.ini

Several settings limit uploads, and you'll usually raise them for real applications:

INI
file_uploads = On            ; uploads enabled at all
upload_max_filesize = 2M     ; maximum size of ONE file (error 1 when exceeded)
post_max_size = 8M           ; maximum size of the WHOLE request body
max_file_uploads = 20        ; maximum number of files per request

post_max_size must be larger than upload_max_filesize (plus room for the other fields). It has a nasty failure mode: when the whole request is larger than post_max_size, PHP throws away the body, and both $_POST and $_FILES are empty, with only a warning in the log. A handler that sees a POST request with an empty $_POST and a CONTENT_LENGTH header should therefore report "upload too large". Web servers have their own limit too (nginx's client_max_body_size defaults to 1 MB), which must also be raised.

Multiple files and the odd $_FILES layout

With name="docs[]", you might expect a list of file arrays. PHP does it the other way round: each key holds an array of values, one per file. This shape is awkward to loop over, so most code normalizes it first:

PHP Normalizing a multiple-file upload

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The same transposed layout appears for named groups like name="files[cv]" and name="files[letter]", with 'cv' and 'letter' as the inner keys.

Checking the real file type with finfo

Never decide a file's type from its name or from $_FILES[...]['type']. Both are sent by the client: an attacker can upload evil.php and call it cat.jpg with type: image/jpeg. Instead, look at the file's contents. The fileinfo extension reads the first bytes (the "magic numbers" that identify formats, like \x89PNG for PNG) and reports the MIME type:

PHP Detecting the real type with finfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The "cat picture" is really PHP code, and finfo says so. getimagesize() returns false for it, which is a useful second check for images. Combine these checks with a whitelist of the types you accept and a size limit, as the storage example below does.

Content sniffing isn't a complete defense on its own: a file can be a valid image and contain PHP code in its metadata. What makes such a file harmless is where and how you store it: a random name with an extension you choose, in a folder the web server never executes. The next section covers that.

Storing uploads safely

Once a file passes validation, move it to permanent storage. Follow these rules:

  1. Use move_uploaded_file($tmp, $target). It moves the file only if $tmp really is a file PHP received in this request, which protects against tricks that make your code "move" /etc/passwd. Use it rather than rename() or copy() for uploads.
  2. Never use the client's file name as the stored name. It may contain ../ (path traversal), a .php extension, characters your file system can't handle, or the name of an existing file. Generate a random name, and pick the extension from the detected type.
  3. Store files outside the web root, for example in storage/uploads/ next to your public/ folder. Serve them through a PHP script that checks permissions and sends them with the right headers. If they must be public, use a folder where the web server is configured never to run scripts, or a separate domain or object storage (S3, R2).
  4. Keep the original name only as data (in the database), for display and for the download file name, escaped like any other user input.
PHP Validating and storing an upload

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call shows move_uploaded_file() doing its job: the file was created by our script, not received in an HTTP upload, so it refuses to move it (and returns false). Passing the mover as a parameter is what makes the function testable; in production you call storeImage($_FILES['avatar'], $storageDir) and the default applies. (A first-class callable like move_uploaded_file(...) as a default parameter value needs PHP 8.5; on older versions, declare ?callable $mover = null and start the function with $mover ??= 'move_uploaded_file';.) The hostile name ../../public/x.php.png never touches the file system: basename() reduces it to x.php.png for display, and the stored name is 32 random hex characters plus an extension chosen from our own list.

For images, the strongest protection is to re-encode them: load the upload with GD (imagecreatefromstring()) and save a fresh PNG, JPEG or WebP. That strips metadata (including GPS location from phone photos, a privacy bonus) and anything hidden inside, and lets you resize huge images at the same time.

Serving stored files

Files stored outside the web root are delivered by a small script, which also lets you check who may download them. The essential headers are the content type, the length, and a Content-Disposition with a safe file name:

PHP
<?php
// download.php?id=42 (read-only example; see the HTTP headers lesson)
$file = findUploadForCurrentUser((int) ($_GET['id'] ?? 0));   // checks permissions
if ($file === null) {
    http_response_code(404);
    exit('Not found');
}

$path = STORAGE_DIR . '/' . $file['stored'];   // our random name, never user input
$downloadName = preg_replace('/[^A-Za-z0-9._-]/', '_', $file['original']);

header('Content-Type: ' . $file['type']);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: attachment; filename="' . $downloadName . '"');
header('X-Content-Type-Options: nosniff');     // browsers must not guess another type
readfile($path);

attachment makes the browser download the file instead of displaying it, which stops an uploaded HTML or SVG file from running scripts on your domain. X-Content-Type-Options: nosniff stops browsers from second-guessing the type. More on headers in HTTP Headers, Status Codes and Redirects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An upload form sends only the file name, not the file. What is most likely missing?

    Without the multipart encoding, the browser submits the form as normal key/value pairs and the file contents are not sent at all.
  2. 2. Which value in a $_FILES entry can you trust?

    error (like tmp_name and size) is set by PHP. name, full_path and type all come from the client and can be anything.
  3. 3. A user uploads a 30 MB file, and post_max_size is 8M. What does the handler see?

    When the request body exceeds post_max_size, PHP discards it entirely, so both arrays are empty. Detect this case by checking for a POST with an empty $_POST and a large CONTENT_LENGTH.
  4. 4. How should you name an uploaded file when storing it?

    Client file names can contain ../, .php extensions or collide with existing files. A random name plus an extension from your own whitelist avoids all of that; store the original name as data.
  5. 5. Why does move_uploaded_file() return false in a script that created the "uploaded" file itself?

    move_uploaded_file() verifies that the source is a genuine uploaded file. That check is what protects you from being tricked into moving arbitrary server files.

Summary

  • Upload forms need method="post" and enctype="multipart/form-data"; accept is only a hint.
  • $_FILES['field'] has name, full_path, type, tmp_name, error and size; only tmp_name, error and size are trustworthy.
  • Check error first (UPLOAD_ERR_OK is 0, UPLOAD_ERR_NO_FILE is 4); know your limits (upload_max_filesize, post_max_size, web server limits). An oversized request empties both $_POST and $_FILES.
  • Multiple uploads (name="docs[]") arrive in a transposed layout; normalize them into a list.
  • Detect the real type from the contents with finfo (and getimagesize() for images), and accept only a whitelist of types under a size limit.
  • Store with move_uploaded_file() under a random name with an extension you choose, outside the web root; keep the original name only as escaped data.
  • Serve stored files through a script with correct Content-Type, Content-Disposition: attachment and X-Content-Type-Options: nosniff.

Next: Cookies