The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web.
Table of Content
When a user submits files through an HTML form, it enables PHP’s $_FILES 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 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 $_FILES, 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.
Understanding the PHP $_FILES Array
Basically, $_FILES 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.
When a file is uploaded via form, the data from that file is stored in $_FILES as:
$_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.enctype="multipart/form-data": This attribute ensures the correct format of all form data, including files, before sending.
Error Checking of PHP $_FILES
When a user submits a file, PHP will process it and store the respective information in the superglobal variable $_FILES. 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.
The upload errors are stored in $_FILES['file']['error'];, 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.
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 $_FILES['file']['error'] and what they mean:
UPLOAD_ERR_INI_SIZE– The uploaded file exceeds theupload_max_filesizedirective in php.ini.UPLOAD_ERR_FORM_SIZE– The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form.UPLOAD_ERR_PARTIAL– Part of the file was uploaded. This could be due to a disruption in the network.UPLOAD_ERR_NO_FILE– No file was uploaded.UPLOAD_ERR_CANT_WRITE– File cannot be written to disk.
PHP $_FILES 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.
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 mime_content_type() function to restrict allowed types and $_FILES['file']['size'] to set a size limit.
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 basename() ensures that directory paths originating from the original filename are removed.
Wrapping Up
Using the $_FILES 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.
So a secure environment from which users, without being wary, can handle files comfortably. Keep in mind that powerful functionality exists with $_FILES, but caution ensures uploads stay secure and reliable.
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.
Similar Reads
You may need to get part of a text when you work with text in PHP. The mb_substr gives you…
The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…
The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…
PHP introduced null to handle undefined or missing values. It helps prevent errors when you check if a variable exists.…
If you are working with PHP and MySQL, one of the first tasks you may need is to create a…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…
The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…
You can assign the boolean data type to PHP variables or use it as a direct value. This enables you…
PHP array_intersect_uassoc checks two or more arrays and returns matches. It compares both the values and the keys with a…
The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…