In this tutorial, you’ll learn how to handle file uploads in PHP using the $_FILES
superglobal, which contains information about files uploaded through an HTML form.
PHP Superglobal $_FILES
1. What is the $_FILES Superglobal?
The $_FILES
superglobal is an associative array that provides details about files uploaded via the HTTP POST method. This array contains information such as the file name, type, size, and any errors encountered during the upload process.
2. HTML Form for File Upload
To upload files, you need an HTML form with the enctype
attribute set to multipart/form-data
. Here’s an example:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" required>
<input type="submit" value="Upload File">
</form>
This form allows users to select a file and submit it to the upload.php
script for processing.
3. Handling File Uploads in PHP
Once the file is uploaded, you can access its information using the $_FILES
superglobal. Here's how to process the uploaded file:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['myFile'];
// Check for upload errors
if ($file['error'] === UPLOAD_ERR_OK) {
// Move the uploaded file to a desired location
move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
echo "File uploaded successfully: " . $file['name'];
} else {
echo "Error uploading file: " . $file['error'];
}
}
?>
This code checks for errors and moves the uploaded file to the uploads
directory.
4. File Upload Error Codes
When handling file uploads, it's essential to check for errors. Here are common error codes returned by the $_FILES
superglobal:
- UPLOAD_ERR_OK: No error, the file uploaded successfully.
- UPLOAD_ERR_INI_SIZE: The uploaded file exceeds the
upload_max_filesize
directive inphp.ini
. - UPLOAD_ERR_FORM_SIZE: The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form.
- UPLOAD_ERR_PARTIAL: The uploaded file was only partially uploaded.
- UPLOAD_ERR_NO_FILE: No file was uploaded.
- UPLOAD_ERR_NO_TMP_DIR: Missing a temporary folder.
- UPLOAD_ERR_CANT_WRITE: Failed to write file to disk.
- UPLOAD_ERR_EXTENSION: A PHP extension stopped the file upload.
5. Security Considerations
When allowing file uploads, it's crucial to consider security. Here are some best practices:
- Validate file types by checking the MIME type and file extension.
- Limit the size of uploads to prevent denial-of-service attacks.
- Store uploaded files outside of the web root to prevent direct access.
- Rename uploaded files to avoid conflicts and ensure unique filenames.
6. Conclusion
The $_FILES
superglobal is essential for handling file uploads in PHP. By understanding how to use this superglobal and following best practices, you can create secure file upload features in your applications.