← Back to PHP Course | Chapter 9: File Handling | Lesson 4 of 8

PHP File Upload

The $_FILES Array

When a file is uploaded to your server through an HTML form, PHP stores all information about that file inside the $_FILES superglobal array, including its original name, MIME type, size, and temporary server location.

Example: The $_FILES Array

php
<?php
$_FILES['photo'] = [
    'name' => 'profile.jpg',
    'type' => 'image/jpeg',
    'size' => 24576,
    'tmp_name' => '/tmp/phpXXXXXX',
];
echo $_FILES['photo']['name'] . " (" . $_FILES['photo']['type'] . ")";
?>

Moving Uploaded Files

Files are initially placed in a temporary folder on the server. To keep them permanently, you must move them to your target directory using move_uploaded_file(), which also verifies the file genuinely came from an HTTP upload.

Example: Moving Uploaded Files

php
<?php
// Simulated for demonstration -- in real use, $_FILES['photo']['tmp_name'] comes from an actual upload
$tmpPath = "data.txt";
file_put_contents($tmpPath, "uploaded content");
$destination = "uploads/photo.txt";
echo "Would move $tmpPath to $destination via move_uploaded_file()";
?>

Verifying File Types

Never trust the file extension or MIME type reported by the browser, since both are easy to spoof — validate the actual file contents (for example, checking image files with getimagesize()) before treating an upload as safe.

Example: Verifying File Types

php
<?php
$_FILES['photo']['name'] = "photo.jpg.php"; // spoofed extension
$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
echo "Reported extension: $ext -- never trust this alone, verify contents instead";
?>

Restricting File Size

Uploading very large files can consume server space and memory, so always check the size key in $_FILES against your project's limits, and make sure your php.ini upload_max_filesize setting matches your intended limit too.

Example: Restricting File Size

php
<?php
$_FILES['photo']['size'] = 5000000;
$maxSize = 2000000;
if ($_FILES['photo']['size'] > $maxSize) {
    echo "File too large";
} else {
    echo "File size OK";
}
?>

Handling Upload Errors

The error key inside $_FILES holds a numeric error code — 0 (UPLOAD_ERR_OK) means success, while other values point to specific problems like exceeding the size limits configured in php.ini.

Example: Handling Upload Errors

php
<?php
$_FILES['photo']['error'] = UPLOAD_ERR_OK;
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
    echo "Upload succeeded";
} else {
    echo "Upload failed with error code " . $_FILES['photo']['error'];
}
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.