File Upload & Download Manager PHP, MySQL

👤 Sharing: AI
```php
<?php

// Database Configuration
$host = 'localhost'; // Database host
$username = 'root';  // Database username
$password = '';      // Database password
$database = 'file_manager'; // Database name

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Create files table if it doesn't exist
$sql = "CREATE TABLE IF NOT EXISTS files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    filepath VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === FALSE) {
    echo "Error creating table: " . $conn->error;
}


// Handle File Upload
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fileToUpload"])) {
    $target_dir = "uploads/"; // Directory where files will be stored
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size (adjust as needed)
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats (adjust as needed)
    $allowed_formats = array("jpg","jpeg","png","gif", "pdf", "doc", "docx", "txt", "zip", "csv", "xls", "xlsx");  // Example allowed formats
    if(!in_array($imageFileType, $allowed_formats)) {
        echo "Sorry, only " . implode(", ", $allowed_formats) . " files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";

            // Store file information in the database
            $filename = basename($_FILES["fileToUpload"]["name"]);
            $filepath = $target_file;

            $sql = "INSERT INTO files (filename, filepath) VALUES ('$filename', '$filepath')";

            if ($conn->query($sql) === TRUE) {
                echo "<br>File information stored in the database.";
            } else {
                echo "<br>Error storing file information: " . $conn->error;
            }


        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}


// Handle File Download
if (isset($_GET['download'])) {
    $file_id = $_GET['download'];

    $sql = "SELECT filename, filepath FROM files WHERE id = $file_id";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $filename = $row['filename'];
        $filepath = $row['filepath'];

        // Check if the file exists
        if (file_exists($filepath)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filepath));
            readfile($filepath);
            exit;
        } else {
            echo "File not found.";
        }
    } else {
        echo "File not found in database.";
    }
}


// Handle File Deletion
if (isset($_GET['delete'])) {
    $file_id = $_GET['delete'];

    $sql = "SELECT filename, filepath FROM files WHERE id = $file_id";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $filename = $row['filename'];
        $filepath = $row['filepath'];

        // Delete the file from the filesystem
        if (unlink($filepath)) {
            // Delete the file information from the database
            $sql = "DELETE FROM files WHERE id = $file_id";
            if ($conn->query($sql) === TRUE) {
                echo "File deleted successfully.";
            } else {
                echo "Error deleting file from database: " . $conn->error;
            }
        } else {
            echo "Error deleting file from the filesystem.";
        }
    } else {
        echo "File not found in database.";
    }
}



?>

<!DOCTYPE html>
<html>
<head>
    <title>File Upload & Download Manager</title>
    <style>
        body {
            font-family: sans-serif;
        }
        table {
            border-collapse: collapse;
            width: 80%;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        a {
            text-decoration: none;
            color: blue;
        }
        a:hover {
            text-decoration: underline;
        }
        .upload-form {
            margin-bottom: 20px;
        }
        .upload-form input[type="file"] {
            margin-bottom: 10px;
        }
        .upload-form input[type="submit"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            cursor: pointer;
        }
        .upload-form input[type="submit"]:hover {
            background-color: #3e8e41;
        }
        .error {
            color: red;
        }

    </style>
</head>
<body>

    <h2>File Upload</h2>
    <div class="upload-form">
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
            Select file to upload:
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload File" name="submit">
        </form>
    </div>

    <h2>Available Files</h2>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Filename</th>
                <th>Upload Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $sql = "SELECT id, filename, upload_date FROM files ORDER BY upload_date DESC";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    echo "<tr>";
                    echo "<td>" . $row["id"]. "</td>";
                    echo "<td>" . $row["filename"]. "</td>";
                    echo "<td>" . $row["upload_date"]. "</td>";
                    echo "<td>
                            <a href='?download=" . $row["id"]. "'>Download</a> |
                            <a href='?delete=" . $row["id"]. "' onclick='return confirm(\"Are you sure you want to delete this file?\")'>Delete</a>
                          </td>";
                    echo "</tr>";
                }
            } else {
                echo "<tr><td colspan='4'>No files uploaded yet.</td></tr>";
            }
            ?>
        </tbody>
    </table>

</body>
</html>

<?php
$conn->close();
?>
```
👁️ Viewed: 6

Comments