Hey, PHP rockstar! Ready to upload files like a pro? Today, we’re diving into file uploads in PHP—handling images, documents, and more while keeping security in check. Let’s get started!
Why File Uploads Matter?
Imagine a website where users can’t upload profile pictures. Boring, right? File uploads are essential for: Profile pictures & avatars, Uploading documents & resumes, Image galleries & file sharing.
But wait! File uploads can be risky if not handled properly. We’ll cover security best practices too!
Setting Up the HTML Form
Let’s start with a simple file upload form.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile">
<button type="submit">Upload File</button>
</form>
The enctype="multipart/form-data"
is required for file uploads!
Writing the PHP Upload Script (upload.php)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uploadDir = "uploads/";
$uploadFile = $uploadDir . basename($_FILES["uploadedFile"]["name"]);
// Check if the file exists
if (file_exists($uploadFile)) {
echo "<p style='color: red;'>File already exists!</p>";
} elseif (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $uploadFile)) {
echo "<p style='color: green;'>File uploaded successfully!</p>";
} else {
echo "<p style='color: red;'>File upload failed!</p>";
}
}
$_FILES["uploadedFile"]["tmp_name"]
contains the temporary file path. move_uploaded_file()
moves it to the uploads folder.
Adding Security to File Uploads
Let’s prevent hackers from uploading malicious files!
Restrict File Types
$allowedTypes = ["image/jpeg", "image/png", "application/pdf"];
if (!in_array($_FILES["uploadedFile"]["type"], $allowedTypes)) {
die("<p style='color: red;'>Invalid file type!</p>");
}
Only allows JPEG, PNG, and PDF files.
Limit File Size
$maxSize = 2 * 1024 * 1024; // 2MB
if ($_FILES["uploadedFile"]["size"] > $maxSize) {
die("<p style='color: red;'>File too large! Max 2MB.</p>");
}
Prevents gigantic uploads from crashing the server.
Rename Files to Prevent Conflicts
$newFileName = uniqid() . "_" . basename($_FILES["uploadedFile"]["name"]);
$uploadFile = $uploadDir . $newFileName;
Prevents overwriting existing files.
Displaying Uploaded Files
Want to show uploaded images? Modify upload.php
:
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $uploadFile)) {
echo "<p style='color: green;'>File uploaded!</p>";
echo "<img src='$uploadFile' width='200'>";
}
Users can see uploaded images instantly!
Congrats! You’ve mastered PHP File Uploads! Today, you learned: How to upload files securely. How to validate file types & sizes. Best security practices to avoid hacks.
0 Comments