The $_FILES superglobal is an associative array of items uploaded to the
current script via the HTTP POST method. It allows you to access file metadata and move
the files to a permanent location on your server.
To upload files, your HTML <form> MUST have the
enctype="multipart/form-data" attribute. Without it, file data will not be
sent.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
When a file is uploaded, PHP populates the $_FILES array with the following
keys:
| Key | Description |
|---|---|
name |
The original name of the file on the user's computer. |
type |
The mime type of the file (e.g., "image/jpeg"). |
tmp_name |
The temporary path where the file is stored on the server. |
error |
The error code associated with this file upload. |
size |
The size of the uploaded file in bytes. |
By default, uploaded files are stored in a temporary directory on the server. To keep
them, you must move them using move_uploaded_file().
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
move_uploaded_file(), the file will be deleted from the temporary directory
as soon as the PHP script finishes executing.
getimagesize() to verify if an uploaded file
is actually an image and not a fake script disguised with an image extension.
enctype="multipart/form-data" in the form.$_FILES array contains 5 essential keys for metadata.tmp_name).move_uploaded_file() to persist the file.