File upload and download are essential features in many websites. Whether it’s for images, documents, or archives, allowing users to upload and download files greatly enhances the user experience. This guide walks you through creating a simple PHP-based file upload and download system with clear examples and explanations.
First, we need an HTML form that allows users to select and upload files:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
In the form above:
Next, create the backend logic in upload.php:
<?php
$targetDir = "uploads/"; // Directory where files will be saved
$targetFile = $targetDir . basename($_FILES["file"]["name"]); // Full upload path
// Check file type
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
$allowedTypes = array("jpg", "jpeg", "png", "gif");
if (!in_array($fileType, $allowedTypes)) {
echo "Only image files are allowed!";
exit;
}
// Move uploaded file
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully!";
} else {
echo "File upload failed!";
}
?>
This PHP script validates file types and moves the uploaded file from a temporary directory to a permanent folder using move_uploaded_file(). In real projects, you should also verify file size, rename files safely, and add security checks to prevent malicious uploads.
After uploading, you can display a list of available files for download. Here’s how to generate the file list:
<?php
$files = glob("uploads/*"); // Retrieve all uploaded files
foreach ($files as $file) {
$fileName = basename($file);
echo "<a href='download.php?file={$fileName}'>{$fileName}</a><br>";
}
?>
This code uses glob() to get all files in the uploads folder and dynamically generates download links.
Then, create a download script download.php:
<?php
$fileName = $_GET["file"];
$filePath = "uploads/" . $fileName;
if (file_exists($filePath)) {
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename={$fileName}");
readfile($filePath);
} else {
echo "File not found!";
}
?>
This script checks if the requested file exists and then sets the proper headers to trigger a download in the browser. For better security, consider sanitizing the filename and validating user access before allowing downloads.
With these examples, you now understand the basics of implementing file upload and download functionality in PHP. While this is a simple demonstration, it provides a solid foundation for beginners to learn file handling in PHP. In production, you can enhance it further by adding file size limits, user permissions, and more advanced security measures.