← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 4 of 8

PHP $_FILES

Accessing File Name and Type

The $_FILES superglobal is a two-dimensional associative array — to access an uploaded file's original name or MIME type, use $_FILES[input_name][name] and $_FILES[input_name][type].

Example: Accessing File Name and Type

php
<?php
$_FILES['avatar'] = ['name' => 'pic.png', 'type' => 'image/png'];
echo $_FILES['avatar']['name'] . " - " . $_FILES['avatar']['type'];
?>

Checking Upload Sizes

The size key in $_FILES holds the file's size in bytes, and checking it against your project's limits before moving the file to a permanent directory avoids wasting disk space on oversized uploads.

Example: Checking Upload Sizes

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

Identifying Upload Errors

The error key inside $_FILES holds a numeric code like UPLOAD_ERR_OK (0) — always check this value first, before touching any other metadata, to confirm the upload actually succeeded.

Example: Identifying Upload Errors

php
<?php
$_FILES['avatar']['error'] = UPLOAD_ERR_OK;
if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
    echo "Upload OK, check other metadata now";
}
?>

Retrieving Temporary Paths

When a file is uploaded, PHP stores it in a temporary directory, with its path saved under the tmp_name key — that temporary path is what you pass to move_uploaded_file() or use for validation.

Example: Retrieving Temporary Paths

php
<?php
$_FILES['avatar']['tmp_name'] = '/tmp/phpABC123';
echo "Temp path: " . $_FILES['avatar']['tmp_name'];
?>

Processing Multiple File Uploads

If a form supports multiple file uploads using array-style input names (like files[]), $_FILES returns nested arrays of values instead of single strings, so you loop through the indices to process each file individually.

Example: Processing Multiple File Uploads

php
<?php
$_FILES['files'] = [
    'name' => ['a.jpg', 'b.jpg'],
    'size' => [1000, 2000],
];
foreach ($_FILES['files']['name'] as $index => $name) {
    echo "$name: " . $_FILES['files']['size'][$index] . " bytes\n";
}
?>
🔒

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.