Allowing users to upload files—such as student profile photos, PDF assignments, and resume documents—is a staple feature of dynamic web applications. However, File Upload is also the #1 most dangerous attack vector in web development if implemented improperly. A hacker uploading an executable .php shell script could gain complete control of your server. In this guide, you will master the $_FILES superglobal and industry-standard security verification techniques.
$_FILES Superglobal AnatomyWhen a file uploads, PHP stores it temporarily in the server's temp directory and populates $_FILES['input_name'] with 5 critical metadata properties:
| Property | Description | Example Value |
|---|---|---|
$_FILES['file']['name'] |
Original client-side filename. | "passport_photo.png" |
$_FILES['file']['tmp_name'] |
Temporary path on the server where file is staged. | "C:\xampp\tmp\php6A1.tmp" |
$_FILES['file']['size'] |
File size measured in bytes (1024 bytes = 1 KB). | 245890 (~240 KB) |
$_FILES['file']['error'] |
Upload status code (0 = UPLOAD_ERR_OK). |
0 |
$_FILES['file']['type'] |
MIME type reported by the browser (untrusted!). | "image/png" |
<?php
$statusMsg = "";
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["avatar"])) {
$file = $_FILES["avatar"];
// 1. Check for upload errors
if ($file["error"] !== UPLOAD_ERR_OK) {
die("Upload failed with error code: " . $file["error"]);
}
// 2. Validate Maximum File Size (Limit: 2 Megabytes = 2 * 1024 * 1024)
$maxSize = 2 * 1024 * 1024;
if ($file["size"] > $maxSize) {
die("Error: File exceeds maximum allowed limit of 2MB.");
}
// 3. Strict Extension Whitelist Validation
$allowedExtensions = ["jpg", "jpeg", "png", "pdf"];
$fileExt = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
if (!in_array($fileExt, $allowedExtensions)) {
die("Error: Only JPG, PNG, and PDF files are permitted.");
}
// 4. Deep MIME Type Verification using Fileinfo (Never trust client MIME!)
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file["tmp_name"]);
finfo_close($finfo);
$allowedMimes = ["image/jpeg", "image/png", "application/pdf"];
if (!in_array($mimeType, $allowedMimes)) {
die("Security Alert: Invalid binary file contents detected.");
}
// 5. Generate Cryptographically Secure Random Filename (Prevent overwrites)
$targetDir = __DIR__ . "/uploads/";
if (!is_dir($targetDir)) {
mkdir($targetDir, 0755, true);
}
$newFileName = bin2hex(random_bytes(16)) . "." . $fileExt;
$destination = $targetDir . $newFileName;
// 6. Move from Temporary Storage to Permanent Destination
if (move_uploaded_file($file["tmp_name"], $destination)) {
$statusMsg = "File uploaded securely as: " . $newFileName;
} else {
$statusMsg = "Server Error: Could not save uploaded file.";
}
}
?>
<!-- HTML Upload Form -->
<form action="" method="POST" enctype="multipart/form-data">
<label>Upload Student ID Proof (Max 2MB):</label><br>
<input type="file" name="avatar" required><br><br>
<button type="submit">Upload File</button>
</form>
<p><?= $statusMsg ?></p>
High-Frequency Exam Question:
Q: What php.ini directives govern file upload limits?
A: Two primary directives:
1. upload_max_filesize: Maximum size allowed for a single uploaded file (default 2M).
2. post_max_size: Maximum data size allowed for the entire POST body (must be larger than upload_max_filesize).
Exercise 29.1: Create an image uploader that accepts only PNG files and displays a thumbnail preview of the uploaded image after submission.
Exercise 29.2: Write a script that checks an upload folder and lists all files with their human-readable size in Megabytes.