$_FILES & move_uploaded_file())Processing file uploads requires strict validation of file sizes, MIME content types, and upload errors to prevent remote code execution (RCE) and security vulnerabilities.
flowchart TD
A["User Submits File Form (enctype='multipart/form-data')"] --> B["PHP Populates $_FILES Array"]
B --> C{"Validate $_FILES['file']['error'] === UPLOAD_ERR_OK"}
C -- Error --> D["Return Upload Error Code"]
C -- Success --> E{"Validate File Size & Allowed MIME Types"}
E -- Invalid --> F["Reject Upload (Invalid Type/Size)"]
E -- Valid --> G["Generate Random Unique Filename"]
G --> H["move_uploaded_file($tmp_name, $target_path)"]
$_FILES Superglobal Array Keys$_FILES['upload']['name']: Original client filename.$_FILES['upload']['type']: Browser-provided MIME type (Never trust!).$_FILES['upload']['tmp_name']: Temporary server storage path.$_FILES['upload']['error']: Upload status code (UPLOAD_ERR_OK = 0).$_FILES['upload']['size']: File size in bytes.<?php
declare(strict_types=1);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['avatar'])) {
$file = $_FILES['avatar'];
// 1. Verify No Upload Error
if ($file['error'] !== UPLOAD_ERR_OK) {
die("Upload Failed with Error Code: " . $file['error']);
}
// 2. Validate File Size Limit (Max 2MB = 2,097,152 Bytes)
if ($file['size'] > 2 * 1024 * 1024) {
die("Security Error: File exceeds 2MB limit.");
}
// 3. Verify Real MIME Type (Do NOT trust $file['type']!)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$realMime = $finfo->file($file['tmp_name']);
$allowedTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
if (!array_key_exists($realMime, $allowedTypes)) {
die("Security Error: Only JPG, PNG, and WebP images are allowed.");
}
// 4. Generate Random Unpredictable Filename
$extension = $allowedTypes[$realMime];
$newFilename = bin2hex(random_bytes(16)) . '.' . $extension;
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 5. Move file from temporary directory to permanent storage
if (move_uploaded_file($file['tmp_name'], $uploadDir . $newFilename)) {
echo "File Uploaded Successfully as: " . $newFilename;
} else {
echo "Error: Failed to move uploaded file.";
}
}
enctype="multipart/form-data" on Form: HTML forms cannot upload files without this attribute.finfo: Never rely on original file extensions or browser-supplied $file['type']..php scripts uploaded as images.What function MUST be used to transfer a temporary uploaded file to its permanent directory destination? (move_uploaded_file())
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.