$_FILES
Last updated onThe PHP superglobal
is a very important utility and great for dealing with file uploads on the web. $_FILES
When a user submits files through an HTML form, it enables PHP's
to access these files; hence, error checking and safe moving to any intended location on the server. Be it an image, a document, or anything else, $_FILES
$_FILES
structures information about an uploaded file in such an orderly way that file handling becomes a piece of cake.
So, by following this tutorial you will learn how to use
, from syntax to best practices for keeping file handling secure. By the end, you will have all the knowledge you need to handle file uploads fearlessly in PHP. $_FILES
Understanding the PHP $_FILES Array
Basically,
is an associative array supplied by PHP to hold all information about uploaded files in a structure with particular keys for easy access to each part of every uploaded file. the PHP Script supplies the name of the file, type of file, size, and temporary location of the file. And upload error. Let's take a closer look now at the basic structure of $_FILES
and what each part does. $_FILES
When a file is uploaded via form, the data from that file is stored in
as: $_FILES
$_FILES['file']['name']; // The name had on the client machine.
$_FILES['file']['type']; // The MIME type of the file (e.g., image/jpeg).
$_FILES['file']['size']; // The size of the file in bytes.
$_FILES['file']['tmp_name']; // The temporary filename as it will be stored on the server.
$_FILES['file']['error']; // The error code associated with this file upload.
Each of them bears some kind of responsibility because all of them serve different purposes that may help you work with an uploaded file. A good example could be setting conditions for what kind of file is allowed to be uploaded or the size limit; only certain formats or sizes could be respectively uploaded using such tools.
Setup Your HTML Form to Upload Files
When you submit a file, PHP uploads it to the server before it can actually process the file. The form needs to be configured correctly, as PHP depends on specific form settings to handle the upload. Here is how to set it up: an HTML form that allows you to choose and upload a file.
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="fileUpload">Select a file:</label>
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload">
</form>
Two important attributes here are:
method="post"
: The upload of the files should be done through the POST method because it can carry more data and is safer.
: This attribute ensures the correct format of all form data, including files, before sending.enctype="multipart/form-data"
Error Checking of PHP $_FILES
When a user submits a file, PHP will process it and store the respective information in the superglobal variable
. When you are handling an upload, you would—in general—want to check if there is a file upload error, followed by validation of the type and size of the uploaded file, before moving it into a folder on your server. $_FILES
The upload errors are stored in
, which will give a code if anything goes wrong in the process of uploading. It is very important to check the file for errors because it can happen that often you don't notice if a file has been uploaded or not. For example, it can be that it only partly uploaded or the file size limit was too low. $
_FILES['file']['error'];
Here is an example that shows how to check if the upload went smoothly:
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
echo "File uploaded successfully.";
} else {
echo "Error during upload. Error code: " . $_FILES['file']['error'];
}
This quick check ensures that you handle only successfully uploaded files and that you may take action if something goes wrong.
Error handling is about making a smooth user experience. Specific feedback based upon an error code is more helpful to users trying to adapt to what went wrong, rather than generic error messages. Here are the list of common error codes in
and what they mean:$_FILES['file']['error']
- The uploaded file exceeds theUPLOAD_ERR_INI_SIZE
upload_max_filesize
directive in php.ini.
- The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form.UPLOAD_ERR_FORM_SIZE
- Part of the file was uploaded. This could be due to a disruption in the network.UPLOAD_ERR_PARTIAL
- No file was uploaded.UPLOAD_ERR_NO_FILE
- File cannot be written to disk.UPLOAD_ERR_CANT_WRITE
PHP
array also has some additional keys that provide you more information about the uploaded file. Anyway, in the following section, you will learn more about each one in detail. Let's move on. $_FILES
Verify File Format and Size Based on $_FILES in PHP
This makes file validation essential from a user experience and security perspective. File type and file size checks ensure that users do not upload files that may cause security issues, whether intentionally or unintentionally.
Use PHP’s
function to restrict allowed types and mime_content_type()
to set a size limit. $_FILES['file']['size']
Here is an example:
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$fileType = mime_content_type($_FILES['file']['tmp_name']);
if (in_array($fileType, $allowedTypes) && $_FILES['file']['size'] < 1000000) {
echo "The file type and size are acceptable.";
} else {
echo "Invalid file type or file is too large.";
}
This approach leads to preventing the upload of a file in an unexpected format or oversized. Makes your application more secure.
Moving the Uploaded File
Once it has been validated, the file must be moved from the temporary location to a permanent folder on the server. PHP has a built-in function to do this task which is
. move_uploaded_file()
It moves the file along with checking whether this file comes from a valid upload or not.
Here is how it works:
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo "File uploaded and saved successfully.";
} else {
echo "Could not write the file.";
}
So the file transfer is secured to a permanent location and
ensures that directory paths originating from the original filename are removed. basename()
Wrapping Up
Using the
superglobal, a PHP developer is able to develop truly dynamic and interactive web applications. It supports file uploads, with knowledge of file validation, error handling, and safety. $_FILES
So a secure environment from which users, without being wary, can handle files comfortably. Keep in mind that powerful functionality exists with
, but caution ensures uploads stay secure and reliable. $_FILES
Integrate these practices into your projects to provide users with a smooth and secure file upload experience. Nobody wants to witness an application go wrong because of a file uploaded. Armed with this knowledge of the variable
. $_FILES
If you need to read more PHP tutorials, click here. Thank you for reading. Happy Coding!
Frequently Asked Questions (FAQs)
How do I use $_FILES to upload files in PHP?`
How can I check for errors when uploading files?`
How do I validate file types and size before uploading?`
How can I secure file uploads in PHP?`
What are common error codes in $_FILES and their meanings?
Can I upload multiple files using $_FILES?