"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to correctly set the Content Type of image display using the Header() function in PHP?

How to correctly set the Content Type of image display using the Header() function in PHP?

Posted on 2025-04-19
Browse:404

How to Determine Correct Content Type for Image Display Using Header() in PHP?

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.

Release Statement This article is reproduced on: 1729203975 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

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