Membuat form upload file dengan PHP dan MySQL

Membuat form upload file dengan PHP dan MySQL

Berikut adalah langkah-langkah untuk membuat form upload file dengan PHP dan MySQL, lengkap dengan kode dan penjelasannya.

Struktur Folder

  1. Database: Tabel untuk menyimpan informasi file yang diunggah.
  2. Form Upload: index.php
  3. Proses Upload: upload_process.php
  4. Folder Penyimpanan: uploads/ (folder untuk menyimpan file yang diunggah).

1. Membuat Tabel MySQL

Buat tabel MySQL untuk menyimpan informasi file yang diunggah.

CREATE DATABASE file_upload;

USE file_upload;

CREATE TABLE uploads (
    id INT AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2. Form Upload File (upload_form.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload File</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Upload File</h2>
        <?php if (isset($_GET['message'])): ?>
            <div class="alert alert-info">
                <?php echo htmlspecialchars($_GET['message']); ?>
            </div>
        <?php endif; ?>
        <form action="upload_process.php" method="POST" enctype="multipart/form-data">
            <div class="mb-3">
                <label for="file" class="form-label">Choose File</label>
                <input type="file" class="form-control" id="file" name="file" required>
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>
    </div>
</body>
</html>
form upload

3. Proses Upload File (upload_process.php)

<?php
// Database connection
$host = 'localhost';
$db = 'file_upload';
$user = 'root'; // Sesuaikan dengan konfigurasi MySQL Anda
$pass = ''; // Sesuaikan dengan konfigurasi MySQL Anda

$conn = new mysqli($host, $user, $pass, $db);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Directory to store uploaded files
    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // Get file information
    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $filePath = $uploadDir . basename($fileName);

    // Move file to the uploads directory
    if (move_uploaded_file($fileTmpName, $filePath)) {
        // Insert file info into the database
        $stmt = $conn->prepare("INSERT INTO uploads (file_name, file_path) VALUES (?, ?)");
        $stmt->bind_param("ss", $fileName, $filePath);

        if ($stmt->execute()) {
            $message = "File uploaded and saved successfully.";
        } else {
            $message = "Error saving file info to the database.";
        }
        $stmt->close();
    } else {
        $message = "Error uploading the file.";
    }

    // Redirect back to the form with a message
    header("Location: upload_form.php?message=" . urlencode($message));
    exit();
} else {
    header("Location: upload_form.php");
    exit();
}
?>

4. Menampilkan File yang Diunggah

Buat halaman untuk menampilkan file yang diunggah. File: file_list.php

<?php
// Database connection
$host = 'localhost';
$db = 'file_upload';
$user = 'root'; // Sesuaikan dengan konfigurasi MySQL Anda
$pass = ''; // Sesuaikan dengan konfigurasi MySQL Anda

$conn = new mysqli($host, $user, $pass, $db);

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

// Fetch uploaded files
$query = "SELECT * FROM uploads ORDER BY upload_date DESC";
$result = $conn->query($query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Uploaded Files</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Uploaded Files</h2>
        <?php if ($result->num_rows > 0): ?>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>File Name</th>
                        <th>Uploaded At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo htmlspecialchars($row['file_name']); ?></td>
                            <td><?php echo $row['upload_date']; ?></td>
                            <td>
                                <a href="<?php echo htmlspecialchars($row['file_path']); ?>" class="btn btn-success btn-sm" download>Download</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No files uploaded yet.</p>
        <?php endif; ?>
    </div>
</body>
</html>
upload

Penjelasan

  1. upload_form.php:
    • Form HTML dengan input file.
    • Menggunakan enctype="multipart/form-data" untuk mendukung pengunggahan file.
  2. upload_process.php:
    • Memindahkan file dari direktori sementara ke folder uploads/.
    • Menyimpan informasi file ke dalam database.
  3. file_list.php:
    • Menampilkan daftar file yang telah diunggah.
    • Memberikan opsi untuk mengunduh file.

Folder uploads/

  • Pastikan folder uploads/ telah dibuat

Jika ada fitur tambahan atau penyesuaian yang diperlukan, beri tahu saya! 😊

Leave a Reply

Your email address will not be published. Required fields are marked *