Current Location: Home> Latest Articles> Complete Guide and Example Code for File Upload in PHP

Complete Guide and Example Code for File Upload in PHP

gitbox 2025-08-04

Understanding File Upload in PHP

File upload is a common feature in web development, especially when users need to submit images, documents, or other files. This guide walks through a practical example of how to implement file uploads using PHP.

Creating the HTML Form

First, we need to create an HTML form that allows users to select a file to upload. Here's a simple example of such a form:

<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>

Note that the enctype="multipart/form-data" attribute is required for file uploads to work. The input type="file" element enables users to select a file from their device.

Writing the PHP Upload Script

Once the form is submitted, a PHP script on the server handles the upload process. Below is an example of upload.php:

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

// Check if the file already exists
if (file_exists($targetFile)) {
    echo "The file already exists.";
} else {
    // Attempt to move the uploaded file
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "The file has been uploaded successfully.";
    } else {
        echo "There was an error uploading your file.";
    }
}
?>

The script uses PHP's $_FILES superglobal to access the uploaded file. basename() is used to retrieve the file name, and move_uploaded_file() moves the file to the target directory.

How the Upload Process Works

Here's a breakdown of how the file upload process works step-by-step:

1. The user selects a file using the HTML form and submits it.

2. The form sends the file to the server via the POST method.

3. The server-side PHP script checks if the file already exists in the target directory.

4. If it doesn't exist, the file is moved from its temporary location to the specified folder.

5. A success or failure message is then returned to the user.

Conclusion

This tutorial demonstrated the complete process of implementing file upload functionality in PHP. From building the HTML form to writing the server-side script, each step plays a crucial role. In real-world applications, developers should also implement validations for file type, file size, and security measures to protect against malicious uploads.

Mastering file upload in PHP is essential for web developers, and we hope this guide helps you build a solid understanding of the topic.