Project 3 – Part 2: File Type & Size Validation

In this part of Project 3 (File Upload System), we will secure our file upload by validating file type and file size.

This prevents:

  • Uploading harmful files
  • Server security issues
  • Storage misuse

What You Will Learn in This Part

  • Validate file extensions
  • Restrict file size
  • Allow only image files
  • Display proper error messages

Why Validation Is Important

Without validation, users can upload:

  • .php files
  • Executable scripts
  • Malware files

⚠️ This can hack your server.

Step 1: Allowed File Types

We will allow only:

  • JPG
  • JPEG
  • PNG
  • GIF
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

Step 2: Maximum File Size

Set file size limit (example: 2MB)

$maxSize = 2 * 1024 * 1024; // 2MB

Step 3: Updated Upload Code with Validation

Update your upload.php file:

<?php
if (isset($_POST['upload'])) {

    $fileName = $_FILES['file']['name'];
    $fileTmp  = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];

    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
    $maxSize = 2 * 1024 * 1024; // 2MB

    if (!in_array($fileExt, $allowedTypes)) {
        echo "<p style='color:red;'>Only JPG, PNG and GIF files are allowed.</p>";
        exit;
    }

    if ($fileSize > $maxSize) {
        echo "<p style='color:red;'>File size must be less than 2MB.</p>";
        exit;
    }

    $newFileName = time() . "_" . $fileName;
    $uploadDir = "uploads/";

    if (move_uploaded_file($fileTmp, $uploadDir . $newFileName)) {
        echo "<p style='color:green;'>File uploaded successfully!</p>";
    } else {
        echo "<p style='color:red;'>File upload failed.</p>";
    }
}
?>

Step 4: Test Validation

Try uploading:

  • .php file → ❌ blocked
  • File > 2MB → ❌ blocked
  • Valid image → ✅ uploaded

Understanding the Code (Simple)

  • pathinfo() → gets file extension
  • in_array() → checks allowed types
  • time() → renames file uniquely
  • exit → stops script on error

Common Beginner Mistakes

  • Forgetting enctype
  • Not checking file size
  • Using MIME type only
  • Not renaming files

Mini Task for Students

Try to:

  • Change max size to 1MB
  • Allow PDF upload
  • Show uploaded image preview

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *