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
file
input 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
$_FILES
stores 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? ๐ค