What are the potential benefits of using a database instead of directories for managing uploaded files in PHP?

Using a database to manage uploaded files in PHP offers several benefits over using directories. With a database, you can easily store additional information about each file, such as metadata or user permissions. This allows for more efficient searching, sorting, and organizing of files. Additionally, databases provide better security measures to protect sensitive files from unauthorized access.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "files_database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Create a table to store uploaded files
$sql = "CREATE TABLE uploaded_files (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
    echo "Table created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

// Insert uploaded file information into the database
$file_name = "example.jpg";
$file_path = "/uploads/example.jpg";

$sql = "INSERT INTO uploaded_files (file_name, file_path) VALUES ('$file_name', '$file_path')";

if ($conn->query($sql) === TRUE) {
    echo "File information inserted successfully";
} else {
    echo "Error inserting file information: " . $conn->error;
}

// Close the database connection
$conn->close();