首頁 > 後端開發 > php教程 > 如何確定 PHP 標頭的正確圖片內容類型?

如何確定 PHP 標頭的正確圖片內容類型?

DDD
發布: 2024-10-18 06:32:02
原創
1024 人瀏覽過

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>
登入後複製

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.

以上是如何確定 PHP 標頭的正確圖片內容類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板