What is $_FILES in PHP: Explanation and Usage
$_FILES is a PHP superglobal array that stores information about files uploaded via an HTML form. It contains details like the file name, type, size, temporary location, and any upload errors, allowing PHP scripts to handle file uploads securely and efficiently.How It Works
Imagine you want to send a package to a friend. You put the item in a box, label it, and send it through a delivery service. In web terms, when a user uploads a file through a form, their browser packages the file and sends it to the server.
PHP uses the $_FILES array to catch this "package". It holds all the important details about the uploaded file, like its original name, size, and where PHP temporarily stored it on the server. This way, your PHP script can check the file, move it to a permanent place, or reject it if something is wrong.
Each uploaded file is represented as an element in $_FILES, with keys like name, type, tmp_name, error, and size. This structure helps you manage uploads safely and easily.
Example
This example shows a simple HTML form to upload a file and a PHP script that uses $_FILES to handle the upload and save the file.
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['userfile']) && $_FILES['userfile']['error'] === UPLOAD_ERR_OK) { $uploadDir = __DIR__ . '/uploads/'; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); } $tmpName = $_FILES['userfile']['tmp_name']; $fileName = basename($_FILES['userfile']['name']); $destination = $uploadDir . $fileName; if (move_uploaded_file($tmpName, $destination)) { echo "File uploaded successfully: " . htmlspecialchars($fileName); } else { echo "Failed to move uploaded file."; } } else { echo "No file uploaded or upload error."; } } ?> <form method="post" enctype="multipart/form-data"> <label for="userfile">Choose a file to upload:</label> <input type="file" name="userfile" id="userfile" required> <button type="submit">Upload</button> </form>
When to Use
Use $_FILES whenever you want to let users upload files to your website or application. Common cases include profile picture uploads, document submissions, or any feature that requires users to send files.
It is important to validate and check the uploaded files using $_FILES to avoid security risks like uploading harmful scripts or very large files. Always check the file size, type, and handle errors properly.
Key Points
$_FILESholds all uploaded file info from HTML forms.- Each file has keys:
name,type,tmp_name,error, andsize. - Files are first saved in a temporary folder; you must move them to a permanent location.
- Always validate files to protect your site from security risks.
- Use
enctype="multipart/form-data"in your form to enable file uploads.
Key Takeaways
$_FILES stores information about files uploaded via HTML forms.$_FILES['file']['error'] to handle upload errors safely.move_uploaded_file().enctype="multipart/form-data" in forms to enable file uploads.