OnlineCBT Logo OnlineCBT
PHP · LESSON 12

File Uploads: $_FILES and move_uploaded_file()

By Ratan Updated: 16 Oct 2026

Handle file uploads securely, validate MIME types, file sizes, and save files to disk.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. HTML Form Configuration for File Uploads

To transmit binary file payloads to the server, the HTML

element must specify two attributes:

  • method="POST"
  • enctype="multipart/form-data"

    
    
    

2. Inspecting the $_FILES Superglobal

When a file is submitted, PHP populates the $_FILES superglobal array with metadata:

 'profile_pic.png',      // Original filename on user computer
//   'type' => 'image/png',            // MIME type reported by browser
//   'tmp_name' => '/tmp/phpYzdqkD',   // Temporary file path on server
//   'error' => 0,                     // UPLOAD_ERR_OK code
//   'size' => 42100                   // File size in bytes
// ]

3. Secure File Upload Implementation

 $maxFileSize) {
        die("File exceeds maximum allowed size (2MB).");
    }

    // 3. Validate file extension using whitelist
    $allowedExtensions = ["jpg", "jpeg", "png", "pdf"];
    $fileExtension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));

    if (!in_array($fileExtension, $allowedExtensions)) {
        die("Invalid file format. Only JPG, PNG, and PDF files are allowed.");
    }

    // 4. Generate random safe filename to avoid overwriting or directory traversal attacks
    $newFileName = bin2hex(random_bytes(16)) . "." . $fileExtension;
    $uploadDirectory = __DIR__ . "/uploads/";

    if (!is_dir($uploadDirectory)) {
        mkdir($uploadDirectory, 0755, true);
    }

    $destination = $uploadDirectory . $newFileName;

    // 5. Safely move uploaded file from temporary storage
    if (move_uploaded_file($file["tmp_name"], $destination)) {
        echo "File successfully uploaded as: " . htmlspecialchars($newFileName);
    } else {
        echo "Failed to save uploaded file.";
    }
}

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat