What is the best way to display an image in PHP, regardless of the file name in the directory?
When displaying an image in PHP, regardless of the file name in the directory, you can use the header() function to set the content type of the response to image/jpeg or image/png based on the file extension. Then, you can read the image file using file_get_contents() and output it using echo.
<?php
// Get the file path from the URL parameter
$file = $_GET['file'];
// Set the content type based on the file extension
if (pathinfo($file, PATHINFO_EXTENSION) == 'jpg' || pathinfo($file, PATHINFO_EXTENSION) == 'jpeg') {
header('Content-Type: image/jpeg');
} elseif (pathinfo($file, PATHINFO_EXTENSION) == 'png') {
header('Content-Type: image/png');
}
// Output the image file
echo file_get_contents($file);
?>
Related Questions
- What is the issue with the PHP code that only sends an email when a user accesses the page with Internet Explorer?
- What are the advantages of using fgetcsv() over explode() when dealing with CSV-like data in PHP?
- What debugging techniques can be used to troubleshoot Telnet commands not being executed in PHP scripts?