Home > Backend Development > PHP Tutorial > How to Determine the Correct Image Content Type for PHP Headers?

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

DDD
Release: 2024-10-18 06:32:02
Original
976 people have browsed it

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:

<code class="php">$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);</code>
Copy after login

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.

The above is the detailed content of How to Determine the Correct Image Content Type for PHP Headers?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template