$_FILES

Last updated on

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

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?`

    To use $_FILES for file uploads, create an HTML form with enctype="multipart/form-data" and method="post". Use PHP to check $_FILES for file data and move the file to a target directory.
    Here is a sample code:
    $targetDirectory = "uploads/";
    $targetFile = $targetDirectory . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
      echo "File uploaded successfully.";
    } else {
      echo "Failed to upload file.";
    }
    
  • How can I check for errors when uploading files?`

    Check $_FILES['file']['error']. If $_FILES['file']['error'] === UPLOAD_ERR_OK, the file uploaded successfully. Otherwise, it returns an error code. For example:
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
      echo "No errors.";
    } else {
      echo "Error code: " . $_FILES['file']['error'];
    }
    
  • How do I validate file types and size before uploading?`

    Use mime_content_type($_FILES['file']['tmp_name']) to check the file type and $_FILES['file']['size'] for size.
    Example:
    $allowedTypes = ['image/jpeg', 'image/png'];
    $fileType = mime_content_type($_FILES['file']['tmp_name']);
    if (in_array($fileType, $allowedTypes) && $_FILES['file']['size'] < 1000000) {
      echo "Valid file type and size.";
    } else {
      echo "Invalid file or too large.";
    }
    
  • How can I secure file uploads in PHP?`

    Rename files upon upload, restrict file types, and store files outside the public directory. Disable executable permissions to prevent script execution.
    Example:
    $targetDirectory = "uploads/";
    $uniqueName = uniqid() . "_" . basename($_FILES['file']['name']);
    $targetFile = $targetDirectory . $uniqueName;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
      echo "Secure file upload completed.";
    } else {
      echo "Failed to secure upload.";
    }
    
  • What are common error codes in $_FILES and their meanings?

    A: Common error codes include:
    - UPLOAD_ERR_INI_SIZE: File exceeds upload_max_filesize in php.ini.
    - UPLOAD_ERR_FORM_SIZE: File exceeds MAX_FILE_SIZE in HTML form.
    - UPLOAD_ERR_PARTIAL: File partially uploaded.
    - UPLOAD_ERR_NO_FILE: No file uploaded.
    - UPLOAD_ERR_CANT_WRITE: Failed to write file to disk.
    Use $_FILES['file']['error'] to check these codes.
  • Can I upload multiple files using $_FILES?

    Yes, set multiple in the <input type="file" multiple name="file[]">. Loop through $_FILES['file']['name'] to handle each file. Example:
    foreach ($_FILES['file']['name'] as $index => $name) {
      if ($_FILES['file']['error'][$index] === UPLOAD_ERR_OK) {
        $targetFile = "uploads/" . basename($name);
        if (move_uploaded_file($_FILES['file']['tmp_name'][$index], $targetFile)) {
          echo "$name uploaded successfully.";
        }
      }
    }
    
Share on: