How to Upload Files in PHP with a Multipart Form

Send the form with POST and multipart/form-data. In PHP, check the upload status in $_FILES and save the temporary file with move_uploaded_file(). This example accepts one JPEG or PNG up to 2 MiB and stores it outside the public folder.

Connect the HTML form to $_FILES

The file input named photo becomes $_FILES['photo'] in PHP. The PHP guide to POST uploads explains the values PHP provides for each upload.

Key Meaning
name Original name supplied by the browser
type Type reported by the browser. Treat it as untrusted.
size Size of the received file in bytes
tmp_name Temporary path PHP uses during the request
error Upload status. UPLOAD_ERR_OK means success.

Check the PHP upload error codes first. The example then uses Fileinfo to identify the temporary file’s MIME type and chooses an extension for an allowed type.

Create the folders and upload page

Use PHP 8 with the Fileinfo extension. Create separate directories for web files and uploads.

If php -m does not list fileinfo, use php --ini to locate your PHP configuration and enable the extension.

  1. Create public and uploads next to each other in your project. Give the PHP process write access to uploads.
  2. Save the complete example as UTF-8 in public/index.php. Keep uploads outside public.
<?php
declare(strict_types=1);

const MAX_BYTES = 2 * 1024 * 1024;

function savePhoto(mixed $file): array
{
    if (!is_array($file) || !is_int($file['error'] ?? null)) {
        return [400, 'Choose a file.'];
    }
    $error = $file['error'];
    if ($error === UPLOAD_ERR_NO_FILE) {
        return [400, 'Choose a file.'];
    }
    if ($error === UPLOAD_ERR_INI_SIZE || $error === UPLOAD_ERR_FORM_SIZE) {
        return [413, 'The file must be 2 MiB or smaller.'];
    }
    if ($error !== UPLOAD_ERR_OK) {
        return [400, 'The file could not be received.'];
    }

    $bytes = $file['size'] ?? null;
    $temp = $file['tmp_name'] ?? null;
    if (!is_int($bytes) || $bytes < 1 || !is_string($temp) || !is_uploaded_file($temp)) {
        return [400, 'The file could not be received.'];
    }
    if ($bytes > MAX_BYTES) {
        return [413, 'The file must be 2 MiB or smaller.'];
    }

    $type = (new finfo(FILEINFO_MIME_TYPE))->file($temp);
    $extensions = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
    if (!is_string($type) || !isset($extensions[$type])) {
        return [415, 'Only JPEG and PNG are accepted.'];
    }

    $directory = dirname(__DIR__) . '/uploads';
    if (!is_dir($directory) || !is_writable($directory)) {
        return [500, 'The file could not be saved.'];
    }
    $name = bin2hex(random_bytes(16)) . '.' . $extensions[$type];
    if (!move_uploaded_file($temp, $directory . '/' . $name)) {
        return [500, 'The file could not be saved.'];
    }

    return [201, 'Saved as' . ' ' . $name];
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    [$status, $message] = savePhoto($_FILES['photo'] ?? null);
    http_response_code($status);
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Upload a photo</title>
</head>
<body>
  <h1>Upload a photo</h1>
  <?php if ($message !== ''): ?>
  <p id="result" role="status"><?= htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>
  <?php endif; ?>
  <form method="post" enctype="multipart/form-data">
    <label for="photo">Choose a JPEG or PNG</label>
    <input id="photo" name="photo" type="file" accept="image/jpeg,image/png" required>
    <p>Maximum file size: 2 MiB</p>
    <button type="submit">Upload</button>
  </form>
</body>
</html>

Test accepted and rejected files locally

Run this command from the project root and open http://127.0.0.1:8000/ in a browser. The built-in server is for local testing.

php -d file_uploads=1 -d upload_max_filesize=3M -d post_max_size=4M -d display_errors=0 -S 127.0.0.1:8000 -t public
  1. Submit a JPEG or PNG up to 2 MiB. The page shows a success message and a random name, and the file appears in uploads.
  2. Submit the same image again to see a different name. A plain text file is rejected by the server even if the browser’s picker allows it.
  3. Try an image slightly above 2 MiB to test the application limit while staying below PHP’s 3 MiB per-file limit.

Diagnose a missing or failed upload

  • If $_FILES is empty, check the form’s enctype, the input name, and file_uploads. Exceeding PHP’s post_max_size can also leave both $_POST and $_FILES empty.
  • upload_max_filesize limits an individual file. Set post_max_size higher as it includes the whole request and multipart overhead. A reverse proxy or web server may impose its own limit.
  • If saving fails, check the PHP logs and the permissions on the temporary and destination directories. Keep internal paths out of visitor-facing messages.

Keep uploaded files outside the web root

move_uploaded_file() moves only files PHP received through HTTP POST. Check the result before reporting success. A server-generated name helps avoid collisions and keeps client-supplied paths out of storage.

Checking MIME type alone does not establish that an image is safe or fully decodable. For a deployed service, follow the OWASP File Upload Cheat Sheet for authentication and authorization, CSRF protection, quotas, inspection or image re-encoding where appropriate, and access-controlled downloads.