Current Location: Home> Latest Articles> Complete PHP File Upload Example with Step-by-Step Explanation

Complete PHP File Upload Example with Step-by-Step Explanation

M66 2025-08-04

Detailed Guide to File Uploads in PHP

File upload is a commonly used feature in web development, allowing users to upload images, documents, or other files. This guide will walk you through a simple and functional PHP file upload implementation, along with a breakdown of the upload process.

Creating the File Upload HTML Form

The first step is to create a frontend form that allows users to select and submit a file to the server.


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

This form uses to enable file selection. The enctype attribute is set to multipart/form-data, which is required for file uploads to work properly.

Writing the PHP Script to Handle the Upload

Now, we’ll create the backend PHP script that processes the file upload:


<?php
$targetDirectory = "uploads/"; // Target directory for uploaded files
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]); // Full path of the uploaded file

// Check if file already exists
if (file_exists($targetFile)) {
    echo "File already exists.";
} else {
    // Attempt to move the uploaded file
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully.";
    } else {
        echo "File upload failed.";
    }
}
?>

Here’s what this script does:

  • $targetDirectory defines where the uploaded files should be stored.
  • basename() gets the name of the uploaded file.
  • move_uploaded_file() is the core function that transfers the file from its temporary location to the target directory.
  • file_exists() is used to prevent overwriting files with the same name.

Understanding the Upload Process

The file upload process can be broken down into the following stages:

Form Submission

When a user selects a file and clicks the upload button, the form data is submitted via POST to the upload.php script on the server.

Server-side Handling

The server receives the file data, checks if the file already exists, and uses move_uploaded_file() to save the file in the specified directory. It then returns a success or failure message based on the outcome.

Conclusion

This tutorial provided a simple yet complete example of how to implement file upload functionality in PHP. We covered both the frontend form and the backend script. File upload is an essential feature in many applications, and understanding its workflow helps developers build secure and efficient systems. You can further enhance this setup with features like file type validation, size limits, and renaming uploaded files to prevent conflicts.