agyanadda@gmail.com

PHP File Upload

PHP Forms and Web 1 min read Updated Dec 1, 2026 Topic 27 of 36

1. The form

<form method="post" enctype="multipart/form-data">
  <input type="file" name="photo" accept="image/*">
  <button>Upload</button>
</form>

Without enctype="multipart/form-data" the file is not sent.

2. $_FILES

Key Meaning
name original file name (do not trust)
tmp_name temporary path on the server
size size in bytes
error UPLOAD_ERR_OK (0) means success

3. Security checks (very important)

  • Check error and a maximum size
  • Check the real type with finfo — not the extension or $_FILES['type'], which can be faked
  • Allow only a short list: jpg, png, webp, pdf
  • Create a new random name: bin2hex(random_bytes(8)) . '.jpg'
  • Save outside public folders when possible, and never allow .php uploads

4. Move the file

move_uploaded_file($tmp, $destination);

Server limits

upload_max_filesize and post_max_size in php.ini decide the maximum upload size.

Example

Example — Secure profile photo upload PHP
<?php
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['photo'])) {
    $file = $_FILES['photo'];
    $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
    $maxBytes = 2 * 1024 * 1024; // 2 MB

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $message = 'Upload failed. Please choose a file.';
    } elseif ($file['size'] > $maxBytes) {
        $message = 'File is larger than 2 MB.';
    } else {
        $mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
        if (!isset($allowed[$mime])) {
            $message = 'Only JPG, PNG or WEBP images are allowed.';
        } else {
            $dir = __DIR__ . '/uploads';
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $newName = bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
            if (move_uploaded_file($file['tmp_name'], "$dir/$newName")) {
                $message = "Uploaded! <br><img src=\"uploads/$newName\" width=\"150\">";
            }
        }
    }
}
?>
<form method="post" enctype="multipart/form-data">
  <input type="file" name="photo" accept="image/*">
  <button>Upload photo</button>
</form>
<p><?= $message ?></p>

Upload a JPG/PNG under 2 MB to see it displayed. A renamed .php or .exe file is rejected because finfo checks the real file type.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which form attribute is required for file uploads?

Exercise 2 True / False

$_FILES['photo']['type'] is safe to trust because the browser sets it.

Exercise 3 Fill in the Blank

movefile() moves the temporary file to its final place.

Frequently Asked Questions

It is bigger than upload_max_filesize or post_max_size in php.ini. Increase them, or show users the limit.