PHP File Upload Handling – Securely Upload Files 📂
Ever wondered how websites allow users to upload images, documents, or memes? PHP makes it easy to handle file uploads, but we need to do it securely!
🔹 Creating a File Upload Form
To upload files in PHP, we need an HTML form with:
- A
fileinput field. enctype="multipart/form-data"(to handle files).- A submit button.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select a file to upload:
<input type="file" name="uploadedFile">
<input type="submit" value="Upload">
</form>
🔹 Handling File Uploads in PHP
When a file is uploaded, it is stored in $_FILES. We use move_uploaded_file() to move it to a permanent location.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["uploadedFile"])) {
$targetDirectory = "uploads/"; // Folder to store uploaded files
$targetFile = $targetDirectory . basename($_FILES["uploadedFile"]["name"]);
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully! 🚀";
} else {
echo "Error uploading the file! ❌";
}
}
?>
🔹 File Upload Security Tips
Uploading files without security can be dangerous! Here are some best practices:
- ✅ Allow only specific file types (e.g., images, PDFs).
- ✅ Set a file size limit to prevent large uploads.
- ✅ Store files in a non-public folder to avoid direct access.
- ✅ Rename files before saving to prevent overwriting.
📝 Example: Secure File Upload
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["uploadedFile"])) {
$targetDirectory = "uploads/";
$fileName = basename($_FILES["uploadedFile"]["name"]);
$targetFile = $targetDirectory . $fileName;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// Allowed file types
$allowedTypes = array("jpg", "png", "gif", "pdf");
// Check file type
if (!in_array($fileType, $allowedTypes)) {
echo "Only JPG, PNG, GIF, and PDF files are allowed!";
exit;
}
// Check file size (limit: 2MB)
if ($_FILES["uploadedFile"]["size"] > 2 * 1024 * 1024) {
echo "File is too large!";
exit;
}
// Move file securely
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile)) {
echo "File uploaded securely! 🎯";
} else {
echo "Error uploading the file!";
}
}
?>
🎯 Key Takeaways
$_FILESstores uploaded file details.move_uploaded_file()moves the file to a safe location.- Always validate file types and sizes before saving.
- Store sensitive files in a non-public directory.
📝 Practice Time!
Try uploading different file types and test the security features. What happens when you upload an unsupported file? 🤔