"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 Determine the Correct Image Content Type for PHP Headers?

How to Determine the Correct Image Content Type for PHP Headers?

Published on 2024-11-05
Browse:151

How to Determine the Correct Image Content Type for PHP Headers?

Determining Image Content Type for PHP Header

When displaying images from outside the web root using the Header() function, users may encounter confusion regarding the specified Content-type: image/png. However, despite the fixed content type, images with various extensions (e.g., JPG, GIF) can still be displayed successfully.

To resolve this discrepancy, it is crucial to dynamically determine the correct image content type based on the file extension. The following code snippet provides a solution:

$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);

By utilizing this approach, the code can identify the correct content type based on the file extension and set the header accordingly. It is worth noting that the correct content type for JPG files is image/jpeg, which should be used instead of the previously confusing image/png.

Release Statement This article is reprinted at: 1729204217 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