File Uploading in PHP: The Complete Beginner’s Guide 🚀

File Uploading in PHP: The Complete Beginner’s Guide 🚀

Ever built a website where users need to upload files, like profile pictures or documents? 📁 Whether it’s an image uploader, a resume submission form, or a content management system, knowing how to handle file uploads securely is essential for PHP developers.

In this step-by-step guide, we’ll cover:
Uploading files with PHP
Validating file types & sizes
Preventing security risks
A mini file upload project

Let’s get started! 🚀


🎯 How PHP Handles File Uploads

PHP processes file uploads using $_FILES, a superglobal array containing:

Key Purpose
$_FILES['file']['name'] Original file name
$_FILES['file']['type'] File MIME type (e.g., image/png)
$_FILES['file']['tmp_name'] Temporary storage location
$_FILES['file']['size'] File size in bytes
$_FILES['file']['error'] Error code (0 = no error)

Before You Start

  1. Make sure your form has enctype="multipart/form-data".
  2. Check php.ini settings:
    • upload_max_filesize = 5M (Sets max file size)
    • post_max_size = 8M (Max size of all POST data)

1️⃣ Creating a Simple File Upload Form

upload.html

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="file"><br>
    <input type="submit" value="Upload">
</form>

🔥 Why?

  • The input type="file" lets users select files.
  • enctype="multipart/form-data" is required for file uploads.

2️⃣ Handling File Uploads in PHP

upload.php

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
    $target_dir = "uploads/"; // Destination folder
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "File uploaded successfully: " . htmlspecialchars($_FILES["file"]["name"]);
    } else {
        echo "Upload failed!";
    }
}
?>

🔥 What’s Happening?

  1. Checks if a file was uploaded (isset($_FILES["file"])).
  2. Moves the file from tmp_name to uploads/.
  3. Prevents XSS by sanitizing the filename (htmlspecialchars()).

3️⃣ Validating File Type & Size

Allow Only Images and Limit Size

<?php
$allowed_types = ["image/jpeg", "image/png", "image/gif"];
$max_size = 2 * 1024 * 1024; // 2MB

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
    $file_type = $_FILES["file"]["type"];
    $file_size = $_FILES["file"]["size"];
    
    if (!in_array($file_type, $allowed_types)) {
        die("Invalid file type. Only JPG, PNG, and GIF allowed.");
    }
    
    if ($file_size > $max_size) {
        die("File too large. Max size is 2MB.");
    }
    
    $target_file = "uploads/" . basename($_FILES["file"]["name"]);
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "File uploaded successfully!";
    } else {
        echo "Upload failed!";
    }
}
?>

🔥 Why?

  • in_array($file_type, $allowed_types) checks MIME types.
  • $file_size > $max_size prevents large files from crashing your server.

4️⃣ Preventing Security Risks

🚨 Never trust user input! Here’s how to secure file uploads:

1. Rename Uploaded Files

$unique_name = uniqid() . "_" . basename($_FILES["file"]["name"]);
$target_file = "uploads/" . $unique_name;

🔍 Why? Prevents duplicate file names and predictable file paths.

2. Block Dangerous Extensions

$disallowed_ext = ["php", "exe", "sh"];
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

if (in_array($file_ext, $disallowed_ext)) {
    die("Invalid file extension!");
}

🔍 Why? Stops users from uploading scripts that could harm your server.


5️⃣ Displaying Uploaded Files

Show Uploaded Images

<?php
$files = scandir("uploads/");
foreach ($files as $file) {
    if ($file != "." && $file != "..") {
        echo "<img src='uploads/$file' width='150'><br>";
    }
}
?>

🔥 Why? scandir("uploads/") lists all uploaded files.


🎯 Mini Project: Profile Picture Uploader

Let’s build a real-world profile picture upload system!

upload.html

<form action="upload.php" method="post" enctype="multipart/form-data">
    Upload Profile Picture: <input type="file" name="profile_pic"><br>
    <input type="submit" value="Upload">
</form>

upload.php

<?php
session_start();
$upload_dir = "profile_pics/";
$allowed_types = ["image/jpeg", "image/png"];
$max_size = 2 * 1024 * 1024; // 2MB

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["profile_pic"])) {
    $file_type = $_FILES["profile_pic"]["type"];
    $file_size = $_FILES["profile_pic"]["size"];
    
    if (!in_array($file_type, $allowed_types)) {
        die("Only JPG and PNG files allowed.");
    }

    if ($file_size > $max_size) {
        die("File too large!");
    }

    $new_name = uniqid() . "_" . basename($_FILES["profile_pic"]["name"]);
    $target_file = $upload_dir . $new_name;

    if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file)) {
        $_SESSION["profile_pic"] = $target_file;
        header("Location: profile.php");
    } else {
        echo "Upload failed!";
    }
}
?>

profile.php

<?php
session_start();
if (!isset($_SESSION["profile_pic"])) {
    echo "No profile picture uploaded.";
} else {
    echo "<img src='" . $_SESSION["profile_pic"] . "' width='200'><br>";
    echo "<a href='upload.html'>Upload New Picture</a>";
}
?>

What’s Happening?

  • upload.php validates and saves the profile picture.
  • Stores file path in $_SESSION["profile_pic"].
  • profile.php displays the uploaded image.

🔥 Boom! You now have a working profile picture uploader! 🚀


🚀 Final Thoughts

Now you can handle file uploads like a pro!
Upload files safely
Validate file types & size
Prevent security risks
Display uploaded images

👉 Next: Handling Errors and Exceptions in PHP

Happy coding! 🎉🚀

1 thought on “File Uploading in PHP: The Complete Beginner’s Guide 🚀

  1. File uploading is pretty tricky, there are a lot of things to talk about file upload, but I only mention the basics here. I will write more about it in future.

Leave a Reply