PHP: Displaying Images with Header() Across Multiple File Formats
In PHP, the header() function is commonly employed to display images that reside outside of the web root. However, this process requires specifying the correct content type, initially set as "image/png," which has raised questions about its applicability to images of various formats.
To resolve this issue, a more comprehensive approach is recommended. Here's how to determine the correct content type based on the file extension:
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename, "."), 1));
switch ($file_extension) {
case "gif":
$ctype = "image/gif";
break;
case "png":
$ctype = "image/png";
break;
case "jpeg":
case "jpg":
$ctype = "image/jpeg";
break;
case "svg":
$ctype = "image/svg xml";
break;
default:
}
header('Content-type: ' . $ctype);
This approach examines the file extension and sets the content type accordingly. Note that the correct content type for JPG files is "image/jpeg." By employing this method, you ensure the correct display of images regardless of their format.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3