👋 Hey there, PHP developer! If you’re building a web application and want to allow users to upload files—images, documents, or anything else—then learning how to upload files in PHP is essential. File uploading is one of the most common features of web apps, and PHP provides built-in tools to handle it securely and efficiently.
In this guide, we’ll walk you through everything you need to know to upload files in PHP. We’ll cover the HTML form, PHP code, validation, and security best practices. Whether you’re a beginner or refreshing your skills, this post will help you handle file uploads like a pro.
Understanding File Upload Basics in PHP
Before diving into the code, let’s understand how PHP handles file uploads.
When a user uploads a file through a form, it gets stored temporarily on the server. PHP provides a global $_FILES
array to access the uploaded file and move it to a permanent location using the move_uploaded_file()
function.
Key Components of File Upload
$_FILES
array – Contains the uploaded file infomove_uploaded_file()
– Moves the file from temp location to your desired directory- HTML form with
enctype="multipart/form-data"
– Required for uploading files
Creating an HTML Form for File Upload
Here’s a simple HTML form that lets users choose a file and submit it.
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label>Select a file to upload:</label><br>
<input type="file" name="myfile"><br><br>
<input type="submit" value="Upload File">
</form>
Explanation:
enctype="multipart/form-data"
: This is mandatory when uploading files.method="POST"
: File data cannot be sent via GET.name="myfile"
: This name is used to retrieve the file via$_FILES['myfile']
.
Writing PHP Code to Handle File Upload
Here’s how to receive and store the uploaded file in upload.php
.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$uploadDir = "uploads/";
$fileName = basename($_FILES["myfile"]["name"]);
$uploadFile = $uploadDir . $fileName;
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $uploadFile)) {
echo "The file ". htmlspecialchars($fileName). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Explanation:
$_FILES["myfile"]["tmp_name"]
: Temporary file path.move_uploaded_file()
: Moves file touploads/
folder.htmlspecialchars()
: Prevents XSS when showing file name.
Validating Uploaded Files (Type, Size)
Security is important when dealing with user uploads. Here’s how you can validate file types and size.
$allowedTypes = ['jpg', 'png', 'gif', 'pdf'];
$maxSize = 2 * 1024 * 1024; // 2MB
$fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$fileSize = $_FILES["myfile"]["size"];
if (!in_array($fileType, $allowedTypes)) {
die("Only JPG, PNG, GIF, and PDF files are allowed.");
}
if ($fileSize > $maxSize) {
die("File size must not exceed 2MB.");
}
Why It Matters:
- Prevents large or unwanted file types from clogging your server.
- Reduces risk of malicious file uploads.
Securing File Uploads
File uploads are vulnerable if not handled carefully. Here are some best practices:
✅ Use a Unique File Name
$newFileName = uniqid() . "." . $fileType;
$uploadFile = $uploadDir . $newFileName;
✅ Restrict File Types
Only allow known, safe file extensions (already shown above).
✅ Prevent PHP Execution in Upload Directory
Create an .htaccess
file in the upload folder:
php_flag engine off
This disables PHP execution in that directory.
Handling Upload Errors
PHP provides built-in error codes for file uploads, which you can check like this:
$error = $_FILES["myfile"]["error"];
if ($error !== UPLOAD_ERR_OK) {
echo "Upload failed with error code: $error";
}
Common Error Codes:
UPLOAD_ERR_INI_SIZE
: Exceeds php.ini sizeUPLOAD_ERR_FORM_SIZE
: Exceeds HTML form limitUPLOAD_ERR_PARTIAL
: Partially uploadedUPLOAD_ERR_NO_FILE
: No file uploaded
Refer to the PHP manual on file upload errors for the full list.
Storing and Organizing Uploaded Files
Organizing uploads into subfolders by date can help in large applications:
$uploadDir = "uploads/" . date("Y/m/d/")."/uniqueFileName.jpg";
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
Now you have structured uploads like:uploads/2025/06/10/uniqueFileName.jpg
Displaying Uploaded Files
To display uploaded images:
<img src="uploads/uniqueFileName.jpg" alt="Uploaded Image">
To show a list of all uploaded files:
$files = scandir("uploads/");
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
echo "<a href='uploads/$file'>$file</a><br>";
}
}
Note:
Use access control if displaying user-specific files.
🎯 Final Thoughts
Uploading files in PHP may seem intimidating at first, but once you understand the $_FILES
array, security practices, and basic file handling, it becomes a very manageable task. From small image uploads to larger media files, PHP offers you everything you need.
Learning how to upload files in PHP is a valuable skill for any web developer. It adds functionality to your apps, from letting users upload profile photos to attaching documents. With the proper security and validation measures in place, file uploads can be both safe and user-friendly.
If you’re planning to build a user portal, a gallery, or even a simple blog with image uploads, you’re now well-equipped to handle that in PHP.
Check out our guide on Handling User Input in PHP to secure form submissions before handling file uploads.
Read the official PHP file upload documentation for a deeper dive into server configurations.
Leave a Reply