Building a file management system in PHP involves creating functionalities to upload, view, download, and delete files. Below is a basic example to help you get started.
Step 1: Directory Structure
Create a directory structure to organize your files and PHP scripts:
- file-management-system/ - uploads/ (Directory to store uploaded files) - db.php (Database connection script) - index.php (Main page to display uploaded files and upload form) - upload.php (Script to handle file uploads) - download.php (Script to handle file downloads) - delete.php (Script to handle file deletion)
Step 2: Database Setup
You may optionally use a database to store metadata about uploaded files. Here’s an example of how you might structure your database:
CREATE TABLE files ( id INT(11) AUTO_INCREMENT PRIMARY KEY, filename VARCHAR(255) NOT NULL, filepath VARCHAR(255) NOT NULL, uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Step 3: PHP Scripts
1. db.php
– Database Connection
<?php $host = 'localhost'; $dbname = 'your_database_name'; $username = 'your_username'; $password = 'your_password'; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("Database connection failed: " . $e->getMessage()); } ?>
2. index.php
– Main Page (List Files and Upload Form)
<?php require_once 'db.php'; // Fetch all uploaded files from the database $stmt = $pdo->query("SELECT * FROM files ORDER BY uploaded_at DESC"); $files = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>File Management System</title> </head> <body> <h1>File Management System</h1> <!-- Upload form --> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" required> <input type="submit" value="Upload File"> </form> <hr> <!-- List of uploaded files --> <?php if ($files): ?> <ul> <?php foreach ($files as $file): ?> <li> <a href="download.php?id=<?= $file['id'] ?>"><?= htmlspecialchars($file['filename']) ?></a> <span>Uploaded on <?= date('F j, Y H:i', strtotime($file['uploaded_at'])) ?></span> <form action="delete.php" method="post" style="display: inline;"> <input type="hidden" name="id" value="<?= $file['id'] ?>"> <input type="submit" value="Delete"> </form> </li> <?php endforeach; ?> </ul> <?php else: ?> <p>No files uploaded yet.</p> <?php endif; ?> </body> </html>
3. upload.php
– File Upload Handling
<?php require_once 'db.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $filename = $_FILES['file']['name']; $filetmp = $_FILES['file']['tmp_name']; $filepath = 'uploads/' . $filename; // Move uploaded file to uploads directory if (move_uploaded_file($filetmp, $filepath)) { // Insert file details into database $stmt = $pdo->prepare("INSERT INTO files (filename, filepath) VALUES (:filename, :filepath)"); $stmt->bindParam(':filename', $filename); $stmt->bindParam(':filepath', $filepath); if ($stmt->execute()) { header("Location: index.php"); exit(); } else { die("Failed to insert file into database."); } } else { die("Failed to upload file."); } } ?>
4. download.php
– File Download Handling
<?php require_once 'db.php'; if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) { $id = $_GET['id']; // Fetch file details from database $stmt = $pdo->prepare("SELECT * FROM files WHERE id = :id"); $stmt->bindParam(':id', $id); $stmt->execute(); $file = $stmt->fetch(PDO::FETCH_ASSOC); if ($file) { $filepath = $file['filepath']; // Download file header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($filepath) . "\""); readfile($filepath); exit(); } else { die("File not found."); } } ?>
5. delete.php
– File Deletion Handling
<?php require_once 'db.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) { $id = $_POST['id']; // Fetch file details from database $stmt = $pdo->prepare("SELECT * FROM files WHERE id = :id"); $stmt->bindParam(':id', $id); $stmt->execute(); $file = $stmt->fetch(PDO::FETCH_ASSOC); if ($file) { // Delete file from uploads directory unlink($file['filepath']); // Delete file record from database $stmt = $pdo->prepare("DELETE FROM files WHERE id = :id"); $stmt->bindParam(':id', $id); if ($stmt->execute()) { header("Location: index.php"); exit(); } else { die("Failed to delete file record from database."); } } else { die("File not found."); } } ?>
Notes
- This example demonstrates basic functionality. For production use, consider adding security measures such as file type validation, authentication, and authorization.
- Ensure proper error handling and user feedback to handle edge cases like file upload failures or database errors.
- Always sanitize and validate user input to prevent security vulnerabilities such as directory traversal attacks.
- Implement additional features based on your requirements, such as file metadata storage, file sharing, or file versioning.
This basic example provides a foundation for building a simple file management system in PHP. Customize and expand upon it according to your specific needs and application requirements.