Why Bother?
Alright, imagine this: You built an awesome website, but it feels… empty. What’s missing? FILES! Whether it’s users uploading cat pictures or downloading top-secret PDFs, handling file uploads and downloads in PHP is a must.
Buckle up! We’re about to dive into the magical world of moving files around like a pro.
Uploading Files: Let’s Accept the Offerings!
Before we start, let’s remember some golden rules:
- Always check the file type – No one wants an "evil_script.exe" uploaded!
- Set a file size limit – Users will try to upload 4GB movies. Trust me.
- Put files in a safe location – Not in your root folder like a rookie!
Step 1: Create the HTML Form
We need a form that allows file uploads. Here’s a simple one:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
Key points:
enctype="multipart/form-data"
is mandatory for file uploads.- The input name (
fileToUpload
) must match what we use in PHP.
Step 2: Handle the Upload in PHP
Here’s upload.php
to process the uploaded file:
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
$maxSize = 2 * 1024 * 1024; // 2MB
$allowedTypes = ["jpg", "png", "pdf", "txt"];
// Check if the file type is allowed
if (!in_array($fileType, $allowedTypes)) {
die("Sorry, only JPG, PNG, PDF, and TXT files are allowed.");
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > $maxSize) {
die("File is too large! Maximum size: 2MB");
}
// Move the file to the uploads folder
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Error uploading file!";
}
Now, users can upload files safely!
Downloading Files: Grabbing the Goodies
What if you want users to download files? Just linking directly is fine for public files, but sometimes you want to force the browser to download instead of opening the file.
Step 1: Create a Download Link
Here’s a simple HTML link to download a file:
<a href="download.php?file=my_document.pdf">Download My Document</a>
Step 2: Write the download.php
Script
Here’s how to force a file download:
if (isset($_GET['file'])) {
$file = "uploads/" . basename($_GET['file']);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "File not found!";
}
}
This script:
- Gets the requested filename from
$_GET["file"]
- Checks if the file exists
- Forces the browser to download the file
Example Case: A Simple File Sharing System
Let’s put it all together! Imagine a system where users can upload and download files. Here’s how it works:
- Users upload files using
upload.php
. - The uploaded files are stored in the
uploads/
directory. - A list of uploaded files is displayed, with a download button next to each file.
List Uploaded Files with Download Links
$files = scandir("uploads");
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
echo "<a href='download.php?file=$file'>$file</a><br>";
}
}
Congrats! You can now upload and download files. Whether it’s profile pictures, invoices, or alien conspiracy documents, you’ve got it covered. Use this power wisely and don’t let users upload anything too weird!
0 Comments