Skip to main content

Lesson 7 of 8

File Uploads - Secure Handling

File uploads are a high-risk feature. PHP exposes uploaded files via $_FILES, but the raw data is full of attacker-controlled values - MIME type, extension, and even filename are easily spoofed. Proper upload handling validates type by content, stores outside the webroot, and generates a safe server-side filename.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Secure File Upload Implementation

Secure File Upload Implementation
<?php
declare(strict_types=1);

function handleImageUpload(array $file): string {
    // ── Step 1: Basic error check ──────────────────────────────
    if ($file["error"] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE   => "File exceeds upload_max_filesize.",
            UPLOAD_ERR_FORM_SIZE  => "File exceeds MAX_FILE_SIZE in form.",
            UPLOAD_ERR_PARTIAL    => "File only partially uploaded.",
            UPLOAD_ERR_NO_FILE    => "No file was uploaded.",
            UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder.",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
        ];
        throw new RuntimeException($errors[$file["error"]] ?? "Unknown upload error.");
    }

    // ── Step 2: Size limit (server-enforced) ───────────────────
    $maxBytes = 5 * 1024 * 1024;   // 5 MB
    if ($file["size"] > $maxBytes) {
        throw new RuntimeException("File must be under 5 MB.");
    }

    // ── Step 3: Verify actual MIME type (NOT $_FILES['type'] - attacker-controlled!) ──
    $finfo    = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file["tmp_name"]);

    $allowedMimes = [
        "image/jpeg" => "jpg",
        "image/png"  => "png",
        "image/webp" => "webp",
        "image/gif"  => "gif",
    ];

    if (!array_key_exists($mimeType, $allowedMimes)) {
        throw new RuntimeException("Only JPEG, PNG, WebP and GIF images are allowed.");
    }

    // ── Step 4: Verify it's actually an image (not a PHP script disguised as JPEG) ──
    if (!getimagesize($file["tmp_name"])) {
        throw new RuntimeException("Uploaded file is not a valid image.");
    }

    // ── Step 5: Generate a safe server-side filename ──────────
    // NEVER use $file["name"] - can contain: ../../../etc/passwd, script.php, etc.
    $extension  = $allowedMimes[$mimeType];
    $safeName   = bin2hex(random_bytes(16)) . "." . $extension;
    // e.g., "a3f8b2c1d4e5f678901234567890abcd.jpg"

    // ── Step 6: Store OUTSIDE the web root ───────────────────
    // Web root: /var/www/html/public/
    // Upload dir: /var/www/html/storage/uploads/ (not web-accessible)
    $uploadDir = dirname(__DIR__) . "/storage/uploads/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $destination = $uploadDir . $safeName;

    // ── Step 7: Move from temp location ──────────────────────
    if (!move_uploaded_file($file["tmp_name"], $destination)) {
        throw new RuntimeException("Failed to move uploaded file.");
    }

    return $safeName;   // return just the filename, store in DB
}

// Usage
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["avatar"])) {
    try {
        $filename = handleImageUpload($_FILES["avatar"]);
        // Save $filename to database linked to the user
        header("Location: /profile?uploaded=1");
        exit;
    } catch (RuntimeException $e) {
        $uploadError = $e->getMessage();
    }
}

Quick Quiz

Tip

Tip

Practice File Uploads Secure Handling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for File Uploads - Secure Handling

Practice Task

Note

Practice Task - (1) Write a working example of File Uploads Secure Handling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with File Uploads Secure Handling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done