How to Handle File Uploads in PHP

This article provides a straightforward guide on how PHP processes file uploads submitted through HTML forms. You will learn how to configure the HTML form correctly, understand the role of the PHP $_FILES superglobal, configure crucial configuration settings, and write a secure backend script to validate and save uploaded files to a server.

1. Setting Up the HTML Form

For PHP to receive a file, the HTML form must meet two strict requirements. First, the form must use the POST method. Second, it must include the enctype="multipart/form-data" attribute. This attribute ensures that the browser splits the file into chunks and sends it correctly.

Here is a basic HTML form structure:

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <label for="fileUpload">Choose a file:</label>
    <input type="file" name="uploaded_file" id="fileUpload">
    <button type="submit" name="submit">Upload</button>
</form>

2. Understanding the PHP $_FILES Superglobal

When a file is submitted, PHP automatically stores information about it in a multi-dimensional associative array called $_FILES.

If your input name is uploaded_file, PHP populates $_FILES['uploaded_file'] with five key-value pairs:

3. Processing and Saving the Uploaded File

By default, uploaded files are saved to a temporary directory on the server. If your script does not move the file, it is automatically deleted at the end of the request.

To save the file permanently, you must use the move_uploaded_file() function. This function verifies that the file is a valid upload and moves it to a directory of your choice.

Here is a practical PHP script to handle this process:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if file was uploaded without errors
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
        
        $fileTmpPath = $_FILES['uploaded_file']['tmp_name'];
        $fileName = $_FILES['uploaded_file']['name'];
        
        // Define the destination path
        $uploadFileDir = './uploads/';
        $dest_path = $uploadFileDir . basename($fileName);
        
        // Create the directory if it does not exist
        if (!is_dir($uploadFileDir)) {
            mkdir($uploadFileDir, 0755, true);
        }

        // Move the file to the target directory
        if (move_uploaded_file($fileTmpPath, $dest_path)) {
            echo "File successfully uploaded and saved.";
        } else {
            echo "There was an error moving the uploaded file.";
        }
    } else {
        echo "Upload failed. Error code: " . $_FILES['uploaded_file']['error'];
    }
}
?>

4. Crucial Security and Validation

Allowing users to upload files is a major security risk. To protect your server, you should implement these basic validation checks before calling move_uploaded_file():

5. Required PHP Configuration Settings

Your PHP configuration file (php.ini) must be configured to allow file uploads. Ensure the following directives are properly set: