PHP File Upload Tutorial with Validation
Learn how to upload files securely in PHP using best practices for size, type, and extension validation.
📂 Why Secure File Uploads Matter
Allowing users to upload files can add great functionality to your website , from profile pictures to document uploads. However, improper handling can lead to serious security vulnerabilities. This guide walks you through building a secure PHP file upload system.
📝 Step 1: Create the Upload Form
<form method="post" enctype="multipart/form-data">
<label>Upload a file:</label><br>
<input type="file" name="uploadedFile" required><br>
<button type="submit" name="uploadBtn">Upload</button>
</form>
⚙️ Step 2: Handle the Upload in PHP
<?php
if (isset($_POST['uploadBtn']) && isset($_FILES['uploadedFile'])) {
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$allowedfileExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
$maxFileSize = 2 * 1024 * 1024; // 2MB
if (in_array($fileExtension, $allowedfileExtensions)) {
if ($fileSize <= $maxFileSize) {
$uploadFileDir = './uploads/';
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$dest_path = $uploadFileDir . $newFileName;
if (move_uploaded_file($fileTmpPath, $dest_path)) {
echo 'File is successfully uploaded.';
} else {
echo 'Error moving the uploaded file.';
}
} else {
echo 'File exceeds the maximum allowed size of 2MB.';
}
} else {
echo 'Upload failed. Allowed file types: ' . implode(', ', $allowedfileExtensions);
}
}
?>
🔐 Security Best Practices
- Never trust the file extension alone , always check the MIME type if possible
- Use
getimagesize()
to validate image uploads - Store uploaded files outside the web root or in protected directories
- Rename files to avoid overwriting and to prevent executing arbitrary code
- Set correct file permissions (e.g., 0644 for files)
✨ Enhancements You Can Add
- Show file preview for image uploads using JavaScript
- Log upload attempts with user info and timestamps
- Scan uploads with antivirus software
- Restrict upload access to logged-in users