PHP
The $_FILES superglobal
Learn to read file info from multipart form data with $_FILES.
The $_FILES superglobal
An HTML form that uploads a file sends the data in multipart format. PHP captures this data with the $_FILES superglobal. Like $_POST, it is accessible from any scope; but it holds file metadata, not text.
The form's enctype attribute must be multipart/form-data. A type="file" field represents the uploaded file. PHP saves the file to a temporary path and gathers its info under $_FILES['avatar'], where avatar is the field's name.
The structure of the $_FILES array
$_FILES['avatar'] is an array with five keys. Each holds a different piece of upload info:
name: the original file name sent by the usertype: the MIME type reported by the browser (e.g. image/png)tmp_name: the temporary path of the file on the servererror: the error code (0 means success)size: the file size in bytes
You access these fields like $file['name']. tmp_name is temporary; PHP deletes it when the script ends, so you must move it for a permanent copy.
Exercise Print file metadata
Define test data for $_FILES['avatar']: name 'profile.jpg', tmp_name '/tmp/phpAbCd.tmp', error 0, size 2048. Then assign it with $file = $_FILES['avatar'] and print three lines: Name: + name, Path: + tmp_name, Size: + size + ' bytes'. End each line with "\n".
Show example solution
First define the $_FILES['avatar'] array, then assign it to $file and echo the three fields.
Example solution:
<?php
// Define $_FILES
$_FILES['avatar'] = [
'name' => 'profile.jpg',
'tmp_name' => '/tmp/phpAbCd.tmp',
'error' => 0,
'size' => 2048
];
$file = $_FILES['avatar'];
echo "Name: " . $file['name'] . "\n";
echo "Path: " . $file['tmp_name'] . "\n";
echo "Size: " . $file['size'] . " bytes\n";
Test yourself
-
Which key holds the temporary path?
Show answer
tmp_name — Correct. tmp_name holds the temporary path of the file.
-
Read the original name
$original = $_FILES['avatar']['____'];
Show answer
$original = $_FILES['avatar']['name'];
-
Match the $_FILES fields
- name
- Original file name
- type
- MIME type
- tmp_name
- Temporary path
- size
- Size in bytes
- error
- Error code
Next lesson: move_uploaded_file()