Working with file uploads and downloads is one of the most common tasks in web applications. PHP makes it easy to upload images, documents, videos, and more using HTML forms and the $_FILES superglobal. Similarly, downloading files can be handled with proper headers.
This guide covers how file upload works, validation, server storage, file downloads, and security practices.
File Uploading in PHP
PHP handles file uploads using a combination of an HTML <form> and backend logic that processes uploaded files.
Step 1: Create an HTML Upload Form
Use the enctype="multipart/form-data" attribute (required for file upload):
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
Step 2: Handle File Upload in PHP
Save this logic in upload.php:
<?php
if (isset($_FILES['myfile'])) {
$file = $_FILES['myfile'];
$fileName = $file['name'];
$fileTmp = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
if ($fileError === 0) {
$destination = "uploads/" . $fileName;
if (move_uploaded_file($fileTmp, $destination)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading the file.";
}
} else {
echo "Upload failed. Error code: " . $fileError;
}
}
?>
Validating File Uploads
Validation is important to ensure security and file integrity.
Validate file type
$allowed = ['jpg', 'png', 'pdf'];
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
exit("Invalid file type");
}
Validate file size (example: 2 MB max)
if ($fileSize > 2 * 1024 * 1024) {
exit("File too large!");
}
Storing Uploaded Files
You can store uploaded files in:
/uploads//storage/- date-wise folders (
uploads/2025/11/) - user-specific directories (
uploads/user_123/)
Use mkdir() if directories don’t exist.
Preventing Duplicate Names
To avoid overwriting files, rename uploaded files:
$newName = time() . "_" . $fileName;
$destination = "uploads/" . $newName;
Or generate a unique ID:
$newName = uniqid() . "." . $ext;
Security Tips for File Uploading
Do not trust file extensions alone
Even .jpg files can contain malicious scripts.
Always validate MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $fileTmp);
if ($mime !== "image/jpeg" && $mime !== "image/png") {
exit("Invalid MIME type");
}
Store files outside the public root (recommended)
Only serve with a controlled script.
Disable direct script execution
For uploads folder, use .htaccess:
php_flag engine off
File Downloading in PHP
File downloading means sending a file to the user’s browser with the correct headers so the browser forces “Save file” instead of displaying it.
Basic File Download Script
<?php
$file = "uploads/report.pdf";
if (file_exists($file)) {
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file));
header("Content-Length: " . filesize($file));
readfile($file);
exit;
} else {
echo "File not found.";
}
?>
Explanation of Download Headers
Content-Type
Tells the browser that the content is a downloadable file.
Content-Disposition
Forces download and sets filename.
Content-Length
Ensures proper downloading progress.
Secure Downloading
Never allow direct user input as file path
Bad:
$file = $_GET['file'];
Good:
$allowedFiles = ['doc1.pdf', 'report.pdf'];
Store files outside public folder
Serve them only through a download script.
File Download Example with Validation
$allowed = ['report.pdf', 'invoice.pdf'];
$file = $_GET['f'];
if (!in_array($file, $allowed)) {
exit("Unauthorized download");
}
$path = "uploads/" . $file;
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$file");
readfile($path);
Practical Use Cases
File Uploading
- Profile picture upload
- Document submission
- Invoice generation and upload
- Media gallery uploads
File Downloading
- Download PDFs or reports
- Invoice download system
- Student notes or assignment downloads
- Backup file download in admin panels
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/