0Pricing
PHP Academy · Lesson

Handling File Uploads

Process uploaded files safely using the _FILES superglobal.

Handling File Uploads is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

PHP File Uploads Overview

PHP handles file uploads through the $_FILES superglobal. The form must use method="POST" and enctype="multipart/form-data".

HTML Upload Form

The HTML form setup for single and multiple file uploads:

<!-- Single file -->
<form method="POST" action="upload.php"
      enctype="multipart/form-data">
    <input type="file" name="document">
    <button>Upload</button>
</form>

<!-- Multiple files -->
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="photos[]" multiple>
    <button>Upload All</button>
</form>

$_FILES Structure

Each uploaded file has five entries in $_FILES:

<?php
$file = $_FILES['document'];

echo $file['name'];      // original name: report.pdf
echo $file['type'];      // browser-reported MIME: application/pdf
echo $file['tmp_name'];  // server temp path: /tmp/phpXXXXXX
echo $file['error'];     // error code: 0 = UPLOAD_ERR_OK
echo $file['size'];      // file size in bytes

Upload Error Codes

Always check $file['error'] before processing:

<?php
$errorMessages = [
    UPLOAD_ERR_INI_SIZE   => 'Exceeds upload_max_filesize in php.ini',
    UPLOAD_ERR_FORM_SIZE  => 'Exceeds MAX_FILE_SIZE in form',
    UPLOAD_ERR_PARTIAL    => 'Only partially uploaded',
    UPLOAD_ERR_NO_FILE    => 'No file uploaded',
    UPLOAD_ERR_NO_TMP_DIR => 'Missing temp folder',
    UPLOAD_ERR_CANT_WRITE => 'Failed to write to disk',
    UPLOAD_ERR_EXTENSION  => 'PHP extension stopped upload',
];

$err = $_FILES['doc']['error'];
if ($err !== UPLOAD_ERR_OK) {
    die($errorMessages[$err] ?? 'Unknown error');
}

Validating File Type Securely

Never trust the browser-provided MIME type — verify with the actual file content:

<?php
$tmp  = $_FILES['image']['tmp_name'];
$allowed = ['image/jpeg', 'image/png', 'image/webp'];

// Check real MIME type from file content
$realMime = mime_content_type($tmp);

if (!in_array($realMime, $allowed)) {
    die('Invalid file type: ' . $realMime);
}

Validating File Size

Enforce server-side size limits even if the HTML form has a MAX_FILE_SIZE hidden field:

<?php
$maxBytes = 5 * 1024 * 1024;  // 5MB
$size     = $_FILES['video']['size'];

if ($size > $maxBytes) {
    $mb = round($size / 1024 / 1024, 2);
    die("File too large: {$mb}MB (max 5MB)");
}

is_uploaded_file and move_uploaded_file

Always use these two functions to confirm the file came via HTTP upload and to move it safely:

<?php
$tmp  = $_FILES['photo']['tmp_name'];
$dest = '/var/www/uploads/' . basename($_FILES['photo']['name']);

if (!is_uploaded_file($tmp)) {
    die('Not an uploaded file — possible attack');
}

if (!move_uploaded_file($tmp, $dest)) {
    die('Failed to move uploaded file');
}

echo 'Upload saved to: ' . $dest;

Generating Safe File Names

Generate a random file name to prevent directory traversal and overwrite attacks:

<?php
$originalName = $_FILES['doc']['name'];
$ext          = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

$allowedExts = ['jpg', 'jpeg', 'png', 'pdf'];
if (!in_array($ext, $allowedExts)) {
    die('File type not allowed');
}

$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$dest     = '/var/www/uploads/' . $safeName;

move_uploaded_file($_FILES['doc']['tmp_name'], $dest);

Handling Multiple File Uploads

When using name="photos[]", $_FILES contains arrays — iterate through them:

<?php
$files = $_FILES['photos'];
$count = count($files['name']);

for ($i = 0; $i < $count; $i++) {
    if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
    
    $tmp  = $files['tmp_name'][$i];
    $ext  = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
    $dest = '/uploads/' . uniqid() . '.' . strtolower($ext);
    
    move_uploaded_file($tmp, $dest);
    echo "Saved: $dest" . PHP_EOL;
}

php.ini Upload Settings

Key php.ini directives that affect file uploads:

  • file_uploads = On — enable uploads
  • upload_max_filesize = 8M — max single file size
  • post_max_size = 32M — max POST body size (must be > upload_max_filesize)
  • max_file_uploads = 20 — max files per request

Image Resizing After Upload

Use the GD library to resize images after upload:

<?php
function resizeImage(string $src, string $dst, int $maxW): void {
    [$w, $h, $type] = getimagesize($src);
    $ratio   = $maxW / $w;
    $newH    = (int) ($h * $ratio);
    $srcImg  = imagecreatefromjpeg($src);
    $dstImg  = imagecreatetruecolor($maxW, $newH);
    imagecopyresampled($dstImg, $srcImg, 0,0,0,0, $maxW, $newH, $w, $h);
    imagejpeg($dstImg, $dst, 90);
    imagedestroy($srcImg);
    imagedestroy($dstImg);
}

Quick Check

Which PHP function is required to safely move an uploaded file to its final destination?

Recap: File Uploads

Upload handling checklist:

  • Form must use method=POST enctype=multipart/form-data
  • Check $_FILES['field']['error'] === UPLOAD_ERR_OK
  • Validate real MIME type with mime_content_type()
  • Validate file size server-side
  • Use move_uploaded_file() — not rename/copy
  • Generate random file names to prevent conflicts

Frequently asked questions

Is the “Handling File Uploads” lesson free?

Yes — the full text of “Handling File Uploads” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Handling File Uploads”?

Process uploaded files safely using the _FILES superglobal. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Handling File Uploads” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with PHP
  2. Writing and Appending to Files
  3. Working with Directories
  4. Handling File Uploads
← Back to PHP Academy