How can PHP be used to generate and download files from a database?
To generate and download files from a database using PHP, you can retrieve the file data from the database, create a file on the server, and then prompt the user to download it. You can use PHP's file handling functions to achieve this.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Retrieve file data from the database
$stmt = $pdo->prepare("SELECT file_data, file_name FROM files WHERE id = :id");
$stmt->bindParam(':id', $_GET['file_id']);
$stmt->execute();
$file = $stmt->fetch();
// Create a file on the server
$file_path = 'downloads/' . $file['file_name'];
file_put_contents($file_path, $file['file_data']);
// Prompt the user to download the file
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file['file_name'] . '"');
readfile($file_path);
// Delete the file from the server
unlink($file_path);
?>
Keywords
Related Questions
- What resources or forums can PHP beginners use to troubleshoot and find solutions to coding issues like the one described in the thread?
- How do IP-based sessions provide additional security for login systems in PHP?
- How can PHP's Exception class be utilized effectively for error handling in a class library?