Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

PHP File Uploads: Handling $_FILES Safely

7 min read Updated By the SkillNewton team

How do file uploads work in PHP?

A PHP file upload starts with an HTML form using method="post" and enctype="multipart/form-data". PHP saves each uploaded file to a temporary location and describes it in the $_FILES array. Your script must check the error code, size and real file type, then move the file with move_uploaded_file() to a safe folder under a new, random name.

The upload form and the $_FILES array

Without enctype="multipart/form-data", the browser sends only the file name, not its contents. The accept attribute helps users pick the right file but is not a security check, because anyone can bypass it. The HTML forms guide covers form markup in general.

<form action="/upload.php" method="post" enctype="multipart/form-data">
  <label for="photo">Profile photo (JPEG, PNG or WebP, up to 2 MB)</label>
  <input type="file" id="photo" name="photo" accept="image/jpeg,image/png,image/webp" required>
  <button>Upload</button>
</form>
$_FILES['photo'] keyContainsTrust it?
nameOriginal file name from the userNo
typeMIME type claimed by the browserNo
sizeSize in bytesYes, measured by PHP
tmp_nameTemporary path on the serverYes
errorAn UPLOAD_ERR_* codeYes

Upload error codes and size limits

Always check error before anything else. The common codes are:

  • UPLOAD_ERR_OK (0): the upload succeeded.
  • UPLOAD_ERR_INI_SIZE (1): larger than upload_max_filesize in php.ini.
  • UPLOAD_ERR_FORM_SIZE (2): larger than a MAX_FILE_SIZE form field.
  • UPLOAD_ERR_PARTIAL (3) and UPLOAD_ERR_NO_FILE (4): only part of the file arrived, or none was chosen.
  • UPLOAD_ERR_NO_TMP_DIR (6), UPLOAD_ERR_CANT_WRITE (7) and UPLOAD_ERR_EXTENSION (8): server-side problems.

Two php.ini settings work together. upload_max_filesize limits each file (2M by default) and post_max_size limits the whole request (8M by default), so it must be larger. When a request exceeds post_max_size, PHP discards it and both $_POST and $_FILES arrive empty, with no error code. max_file_uploads caps the number of files per request. Your web server may have its own body size limit as well.

; php.ini
upload_max_filesize = 5M
post_max_size = 6M
max_file_uploads = 10

A secure upload handler step by step

  1. Check the CSRF token, as described in the PHP security guide.
  2. Confirm $_FILES['photo']['error'] is an integer equal to UPLOAD_ERR_OK.
  3. Enforce your own size limit with size.
  4. Detect the real type from the file contents with finfo and compare it with an allow-list.
  5. Generate a random file name and choose the extension from the detected type.
  6. Move the file with move_uploaded_file() into a folder outside the public web root.
<?php
// public/upload.php
declare(strict_types=1);

const MAX_BYTES  = 2 * 1024 * 1024;
const ALLOWED    = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
const UPLOAD_DIR = __DIR__ . '/../storage/uploads/';

function fail(string $message): never
{
    http_response_code(400);
    exit($message);
}

if (empty($_FILES) && (int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 0) {
    fail('The request was larger than the server allows.');
}

$file = $_FILES['photo'] ?? null;
if (!is_array($file) || !is_int($file['error'])) {
    fail('Please upload exactly one file.');
}

match ($file['error']) {
    UPLOAD_ERR_OK => null,
    UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => fail('The file is too large.'),
    UPLOAD_ERR_NO_FILE => fail('Please choose a file.'),
    default => fail('The upload failed. Please try again.'),
};

if ($file['size'] > MAX_BYTES) {
    fail('The file is larger than 2 MB.');
}

$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
if ($mime === false || !array_key_exists($mime, ALLOWED)) {
    fail('Only JPEG, PNG and WebP images are allowed.');
}

$name = bin2hex(random_bytes(16)) . '.' . ALLOWED[$mime];
if (!move_uploaded_file($file['tmp_name'], UPLOAD_DIR . $name)) {
    fail('The server could not save the file.');
}
echo 'Uploaded as ' . $name;

The size check against MAX_BYTES matters even though PHP has its own limits, because upload_max_filesize is usually set for the whole site while each form may need a different limit. A hidden MAX_FILE_SIZE form field only gives the browser a hint; never rely on it. On sites that accept files from the public, scanning uploads with antivirus software before anyone else downloads them adds another layer of protection.

move_uploaded_file() only moves files that PHP received through an upload, which stops a forged tmp_name from copying a server file such as a configuration file. The random name prevents overwriting, path tricks like ../ and names such as shell.php.jpg.

Storing files outside the web root and serving them

If uploads land in a public folder, a file that slips through your checks may be run as a script when someone requests its URL. Store uploads outside the document root, then serve them through a small PHP script that validates the name and sends safe headers.

<?php
// public/photo.php?f=<32 hex characters>.jpg
$name = (string) ($_GET['f'] ?? '');
if (!preg_match('/^[a-f0-9]{32}\.(jpg|png|webp)$/', $name, $m)) {
    http_response_code(404);
    exit;
}
$path = __DIR__ . '/../storage/uploads/' . $name;
if (!is_file($path)) {
    http_response_code(404);
    exit;
}
$types = ['jpg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp'];
header('Content-Type: ' . $types[$m[1]]);
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . (string) filesize($path));
readfile($path);

This script is also the right place to check permissions, for example that the logged-in user owns the file. The strict pattern makes path traversal impossible; the regular expressions guide explains how it works. If you must store files in a public folder, configure the web server never to execute scripts there.

Re-encoding images to remove hidden content

A file can be a valid image and still carry extra data, such as camera location metadata or an embedded payload. Re-encoding with the GD extension creates a clean new image from the pixels alone. Check dimensions first with getimagesize(), so a small file that expands into a huge image cannot exhaust memory.

<?php
// Replace the move_uploaded_file() step with this
[$width, $height] = getimagesize($file['tmp_name']) ?: [0, 0];
if ($width < 1 || $height < 1 || $width > 4000 || $height > 4000) {
    fail('Image dimensions are not allowed.');
}
$image = imagecreatefromstring((string) file_get_contents($file['tmp_name']));
if ($image === false) {
    fail('The image could not be read.');
}
imagesavealpha($image, true);   // keep PNG and WebP transparency
$target = UPLOAD_DIR . bin2hex(random_bytes(16)) . '.' . ALLOWED[$mime];
$saved = match ($mime) {
    'image/jpeg' => imagejpeg($image, $target, 85),
    'image/png'  => imagepng($image, $target),
    'image/webp' => imagewebp($image, $target, 85),
};
if (!$saved) {
    fail('The server could not save the image.');
}

Re-encoding also normalises the output: every saved image has a known format, a known extension and no metadata. Resizing at the same time, for example to a maximum width of 1200 pixels, saves storage and bandwidth. Image processing uses a lot of memory, so test with the largest dimensions you allow and adjust memory_limit if needed.

Accepting several files in one form

With name="photos[]" and the multiple attribute, PHP groups each key into its own array. Convert that into one array per file before validating:

<?php
$files = [];
foreach ($_FILES['photos']['error'] ?? [] as $i => $error) {
    $files[] = [
        'error'    => $error,
        'size'     => $_FILES['photos']['size'][$i],
        'tmp_name' => $_FILES['photos']['tmp_name'][$i],
    ];
}
// Now validate each entry in $files exactly like a single upload

Practical exercise: a private profile photo uploader

On your own machine, build an upload page for a logged-in test user, using the session setup from the sessions and cookies guide.

  • Accept one JPEG, PNG or WebP image up to 2 MB and re-encode it with GD.
  • Save it in storage/uploads/, outside public/, and record the random name against the user ID in the database.
  • Show the photo through photo.php, refusing requests from other users.
  • Display a friendly message for each error case.

You are done when a 5 MB file, a text file renamed to .jpg and an empty submission each show a clear error, and a valid image appears on the profile page. File handling is part of the PHP foundation course.

Common mistakes

  • Forgetting enctype="multipart/form-data", so $_FILES stays empty.
  • Trusting $_FILES['photo']['type'] or the file extension, both of which the user controls.
  • Saving files under their original names, which allows overwrites and path tricks.
  • Storing uploads in a public folder where the server may execute them as scripts.
  • Raising upload_max_filesize without also raising post_max_size.
  • Using copy() or rename() on the temporary file instead of move_uploaded_file().

Frequently asked questions

Why is $_FILES empty even though I chose a file?

Check three things: the form has enctype="multipart/form-data" and method="post", file_uploads is enabled in php.ini, and the request is smaller than post_max_size.

What happens to the temporary file if I do not move it?

PHP deletes it automatically when the request ends, so you must move or process it during that request.

Can I show upload progress?

Yes, from the browser. Sending the file with XMLHttpRequest lets JavaScript read upload progress events while PHP handles the request as normal.

Should I store uploaded files in the database?

Usually not. Store the file on disk or in object storage, and keep only its random name, type, size and owner in the database.

Want to Learn This Properly?

The PHP Web Development: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.