How can PHP be used to read files from a database and display them in different formats?
To read files from a database and display them in different formats using PHP, you can retrieve the file data from the database, determine the file type, and then display it accordingly. You can use PHP's file handling functions to read the file data and output it in the desired format, such as displaying an image file as an image or a text file as text.
// Assume $db is the database connection
// Retrieve file data from the database
$query = "SELECT file_data, file_type FROM files WHERE id = 1";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
// Determine the file type
$fileType = $row['file_type'];
// Display the file data in the appropriate format
if ($fileType === 'image/jpeg' || $fileType === 'image/png') {
header('Content-Type: ' . $fileType);
echo $row['file_data'];
} elseif ($fileType === 'text/plain') {
echo $row['file_data'];
} else {
echo 'Unsupported file type';
}
Keywords
Related Questions
- How can the issue of redeclaring functions be avoided when using require_once in PHP?
- What are the best practices for normalizing database structures in PHP to avoid issues like inconsistent or duplicate data?
- How can one resolve the issue of not being able to connect to the IMAP server when trying to use SquirrelMail on a local server with XAMPP?