PHP File Upload Tutorial (Examples + Security Tips)

Introduction

Uploading files is a very common feature in PHP applications. Users often upload images, documents, PDFs, and other files through forms.

For example:

  • Profile picture uploads
  • Resume uploads
  • Document submissions
  • Image galleries

In this tutorial, you will learn how file upload works in PHP step by step, along with important security best practices.

What You Will Learn

  • How file upload works in PHP
  • How to create a file upload form
  • How to use the $_FILES array
  • How to upload files using move_uploaded_file()
  • How to validate file type and size
  • Important security tips to protect your application

How File Upload Works in PHP

PHP uses the $_FILES superglobal to handle file uploads.

Basic Process:

  1. Create an HTML form
  2. Use method="post"
  3. Add enctype="multipart/form-data"
  4. Access file data using $_FILES
  5. Move file to a desired directory

Creating the File Upload Form

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <button type="submit">Upload File</button>
</form>

Important Attributes

  • method="post" → Required
  • enctype="multipart/form-data" → Required for file upload

Understanding $_FILES Array

When a file is uploaded, PHP stores its information in the $_FILES array.

$_FILES['myfile'];

Common properties:

  • name → Original file name
  • type → File type
  • tmp_name → Temporary file path
  • size → File size
  • error → Upload error code

Uploading the File Using PHP

The move_uploaded_file() function is used to move the file from temporary location to a permanent folder.

$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["myfile"]["name"]);

if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile)) {
    echo "File uploaded successfully.";
} else {
    echo "File upload failed.";
}

Output

File uploaded successfully.

Validating File Type (Important)

Always restrict file types for security.

$allowedTypes = ["jpg", "png", "pdf"];
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

if (in_array($fileType, $allowedTypes)) {
    move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile);
} else {
    echo "Invalid file type.";
}

Checking File Size

Limit the file size to prevent server overload.

if ($_FILES["myfile"]["size"] > 2000000) {
    echo "File is too large.";
}

(2MB limit example)

Handling Upload Errors

Always check for upload errors.

if ($_FILES["myfile"]["error"] === 0) {
    // upload file
} else {
    echo "Error uploading file.";
}

Renaming Uploaded Files (Best Practice)

Avoid duplicate names and security issues by renaming files.

$fileName = time() . "_" . basename($_FILES["myfile"]["name"]);
$targetFile = $targetDir . $fileName;

Understanding File Paths in PHP

Use correct paths when saving files.

$targetDir = __DIR__ . "/uploads/";

👉 __DIR__ ensures the correct directory path.

Real-World Example: Uploading Profile Images

$targetDir = "uploads/";
$fileName = time() . "_" . basename($_FILES["myfile"]["name"]);
$targetFile = $targetDir . $fileName;

$allowedTypes = ["jpg", "png"];

$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

if ($_FILES["myfile"]["error"] === 0) {

    if ($_FILES["myfile"]["size"] <= 2000000) {

        if (in_array($fileType, $allowedTypes)) {

            if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile)) {
                echo "Image uploaded successfully.";
            } else {
                echo "Upload failed.";
            }
        } else {
            echo "Invalid file type.";
        }

    } else {
        echo "File too large.";
    }

} else {
    echo "Error uploading file.";
}

Common Errors and Fixes

Error 1: File Not Uploading

👉 Check folder exists and path is correct

Error 2: Permission Denied

👉 Set folder permission to 755 or 775

Error 3: File Always Fails

👉 Check $_FILES["myfile"]["error"]

Important Security Tips

  • Always validate file type
  • Limit file size
  • Rename uploaded files
  • Store uploads outside public folders if possible
  • Never allow executable files
  • Sanitize file names

Common Mistakes to Avoid

  • Forgetting enctype="multipart/form-data"
  • Allowing all file types
  • Not checking file size
  • Uploading files without validation
  • Not renaming files

FAQs

Why is my file not uploading?

Check form enctype, file permissions, and error code.

What is the maximum file upload size in PHP?

It depends on php.ini settings (upload_max_filesize).

Can PHP upload multiple files?

Yes, using array inputs in forms.

Summary

  • PHP file upload uses $_FILES
  • move_uploaded_file() is used to save files
  • Validation is mandatory for security
  • File uploads must be handled carefully

Practice Task

  • Create a file upload form
  • Allow only images (jpg, png)
  • Limit size to 2MB
  • Rename uploaded files
  • Display success or error message

In the next tutorials, you’ll learn about File Permissions & Security in PHP – chmod(), File Access & Best Practices.

Related Tutorials

Leave a Reply

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