简体   繁体   English

PHP:如何提供正确的内容类型(取决于文件扩展名?)?

[英]PHP: how to serve right content-type (depending on file extension?)?

I'm using the scripts below to gzip some CSS and JS files. 我正在使用以下脚本gzip一些CSS和JS文件。 It works nice - except for serving JS files with the wrong content-type (and not the appropriate application/x-javascript). 效果很好-除了使用错误的内容类型(而不是适当的application / x-javascript)提供JS文件之外。 How could I improve the PHP code in order to serve the right content-type? 如何改善PHP代码以提供正确的内容类型? Thanks! 谢谢!

.htaccess: 的.htaccess:

AddHandler application/x-httpd-php .css .js
php_value auto_prepend_file gzip.php

gzip.php: gzip.php:

<?php 
ob_start ("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 ;
$ExpStr = "Expires: " . 
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>

You could check the ending of the requested URL path: 您可以检查所请求的URL路径的结尾:

$_SERVER['REQUEST_URI_PATH'] = strtok($_SERVER['REQUEST_URI'], '?');
$extensionToType = array(
    '.css' => 'text/css;charset=utf-8',
    '.js'  => 'application/javascript;charset=utf-8'
);
$extension = strrchr($_SERVER['REQUEST_URI_PATH'], '.');
if (isset($extensionToType[$extension])) {
    header("Content-type: ".$extensionToType[$extension]);
} else {
    header("Content-type: application/octet-stream");
}

您也可以使用FileInfo而不是使用扩展名来检查mime类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM