PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web.

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 the upload_max_filesize directive 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

PHP abs Function: How to Get Absolute Values

The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…

PHP Null Coalescing Operator: Handling Null Values

The PHP null coalescing operator, written as ??, is a helpful feature added in PHP 7. It makes it easier…

PHP OOP Constructor: How It Works in a Class with Examples

The OOP constructor initializes an object when it is created in PHP. Understand What a Constructor Is in PHP A…

PHP array_combine: How to Merge Arrays as Key and Value

The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…

PHP Type Juggling: How it Works Behind the Scenes

PHP type juggling refers to the dynamic system where the type of a variable is determined by its context in…

PHP OOP Programming: A Complete Tutorial

A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming…

How to Use PHP count() to Get Array Length

PHP developers may be need to determine the number of elements in an array. The count() function in PHP makes…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP is_readable: Check File Accessibility

The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…

PHP array_key_exists: How it Works with Examples

The PHP array_key_exists function checks a given key in an array and tells if that key exists or not. Understand…

Previous Article

PHP $_POST: Handling Form Data in PHP

Next Article

PHP $_COOKIE: Securely Store and Manage Data

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.