PHP $_FILES
In this page:
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
$_FILES['avatar'] = ['name' => 'pic.png', 'type' => 'image/png'];
echo $_FILES['avatar']['name'] . " - " . $_FILES['avatar']['type'];
?>
Login to try C/C++/Java/PHP code in the editor
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
$_FILES['avatar']['size'] = 3000000;
$maxSize = 2000000;
if ($_FILES['avatar']['size'] > $maxSize) {
echo "File too large";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$_FILES['avatar']['error'] = UPLOAD_ERR_OK;
if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
echo "Upload OK, check other metadata now";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$_FILES['avatar']['tmp_name'] = '/tmp/phpABC123';
echo "Temp path: " . $_FILES['avatar']['tmp_name'];
?>
Login to try C/C++/Java/PHP code in the editor
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
$_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";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: