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:
name: The original name of the file on the user’s computer (e.g.,document.pdf).type: The MIME type of the file as reported by the browser (e.g.,application/pdf).tmp_name: The temporary path where the file is stored on the server immediately after upload.error: An error code representing the status of the upload. A value of0(UPLOAD_ERR_OK) means the upload was successful.size: The size of the file in bytes.
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():
- Validate File Size: Limit the maximum file size in
your script by checking
$_FILES['uploaded_file']['size']. - Restrict File Extensions: Only allow specific
extensions (like
.jpg,.png, or.pdf). Usepathinfo()to extract and check the extension. - Verify MIME Type: Do not trust the file extension
alone. Use PHP’s
finfo_file()function to inspect the actual binary content of the file. - Sanitize Filenames: Use
basename()to prevent directory traversal attacks, and consider renaming the file to a random string or UUID to avoid overwriting existing files.
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:
file_uploads = On: Enables HTTP file uploads.upload_max_filesize = 2M: The maximum size allowed for a single uploaded file.post_max_size = 8M: The maximum size of POST data that PHP will accept. This must be larger thanupload_max_filesize.upload_tmp_dir: Specifies the temporary directory where files are stored during the upload process (if not set, system defaults are used).