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.
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.
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:
The file upload process can be broken down into the following stages:
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.
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.
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.