PHP File Upload: A Complete Guide to Securely Handling File Uploads in PHP

Last updated 3 months, 4 weeks ago | 312 views 75     5

Tags:- PHP

Introduction: Why PHP File Uploads Matter

File uploads are an essential part of many web applications—profile pictures, PDF forms, product images, and document submissions all rely on user uploads. PHP provides a straightforward way to handle file uploads using the $_FILES superglobal, but if not done properly, it can expose your site to security vulnerabilities like code injection or file tampering.

This guide will teach you how to securely upload files in PHP, step by step, with full code examples and tips to avoid common pitfalls.


How PHP File Upload Works

When a user submits a form with enctype="multipart/form-data" and a file input, PHP stores the uploaded file in a temporary directory and populates the $_FILES array with file data.

Structure of $_FILES['input_name']

Array
(
    [name] => example.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/phpA1B.tmp
    [error] => 0
    [size] => 45678
)

Step-by-Step File Upload in PHP

Step 1: HTML Form for Upload

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

Step 2: Handle Upload in upload.php

<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

// Get file extension
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if actual file is uploaded
if (isset($_POST["submit"])) {
    if (file_exists($_FILES["fileToUpload"]["tmp_name"])) {
        echo "File is selected.<br>";
    } else {
        echo "No file uploaded.<br>";
        $uploadOk = 0;
    }
}

// File size limit (e.g., 2MB)
if ($_FILES["fileToUpload"]["size"] > 2000000) {
    echo "Sorry, your file is too large.<br>";
    $uploadOk = 0;
}

// Allow only certain file types
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
if (!in_array($imageFileType, $allowedTypes)) {
    echo "Only JPG, PNG, GIF, and PDF files are allowed.<br>";
    $uploadOk = 0;
}

// Final check and move file
if ($uploadOk) {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
    } else {
        echo "Error uploading your file.";
    }
} else {
    echo "File was not uploaded due to errors.";
}
?>

✅ Full Functional Code Example

upload_form.html

<form action="upload_handler.php" method="post" enctype="multipart/form-data">
  <label>Select file to upload:</label>
  <input type="file" name="fileToUpload" />
  <button type="submit" name="submit">Upload</button>
</form>

upload_handler.php

<?php
$uploadDir = "uploads/";
$filename = basename($_FILES["fileToUpload"]["name"]);
$targetFile = $uploadDir . $filename;
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Validate file type
$allowed = ["jpg", "jpeg", "png", "pdf"];
if (!in_array($fileType, $allowed)) {
    echo "Error: Only JPG, JPEG, PNG, and PDF files are allowed.";
    $uploadOk = 0;
}

// Validate file size
if ($_FILES["fileToUpload"]["size"] > 2 * 1024 * 1024) {
    echo "Error: File is too large (max 2MB).";
    $uploadOk = 0;
}

// Upload file
if ($uploadOk) {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "File " . htmlspecialchars($filename) . " uploaded successfully.";
    } else {
        echo "Error: File upload failed.";
    }
}
?>

Tips & Common Pitfalls

✅ Best Practices

  • Always check MIME type and extension to allow only specific file types.

  • Set file size limits to avoid server overloads.

  • Store files outside the web root or use randomized names to prevent direct access.

  • Use move_uploaded_file() — it's secure and built for uploads.

  • Use htmlspecialchars() to safely display uploaded filenames.

❌ Common Mistakes

  • Not validating file type or size, opening security holes.

  • Storing files in public folders without access restrictions.

  • Using copy() instead of move_uploaded_file().

  • Trusting the MIME type alone — always double-check extensions.


Comparison Table: file_put_contents() vs. move_uploaded_file()

Function Use Case Secure for Uploads Notes
file_put_contents() Write basic file content ❌ No Not safe for handling file uploads
move_uploaded_file() Handle uploaded file safely ✅ Yes Recommended method for uploads

Folder Permissions for Uploads

Make sure the destination upload folder (e.g., uploads/) has correct permissions:

chmod 755 uploads/

Avoid using 777 as it’s a major security risk.


Conclusion: Secure File Uploads in PHP

Uploading files in PHP is simple—but doing it safely is key.

✅ Quick Recap:

  • Use an HTML form with enctype="multipart/form-data"

  • Validate file types and size

  • Move the file securely using move_uploaded_file()

  • Avoid common security pitfalls

Once mastered, PHP file uploads unlock the power to build user-driven applications like profile image uploaders, resumes submission, or media libraries.