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

发布于 2024-08-18 10:40:50 字数 548 浏览 2 评论 0原文

我正在使用下面的脚本来 gzip 一些 CSS 和 JS 文件。它工作得很好 - 除了使用错误的内容类型(而不是适当的 application/x-javascript)提供 JS 文件。如何改进 PHP 代码以提供正确的内容类型?谢谢!

.htaccess:

AddHandler application/x-httpd-php .css .js
php_value auto_prepend_file 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);
?>

I'm using the scripts below to gzip some CSS and JS files. It works nice - except for serving JS files with the wrong content-type (and not the appropriate application/x-javascript). How could I improve the PHP code in order to serve the right content-type? Thanks!

.htaccess:

AddHandler application/x-httpd-php .css .js
php_value auto_prepend_file 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);
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听闻余生 2024-08-25 10:40:50

您可以检查请求的 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");
}

You could check the ending of the requested URL path:

$_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");
}
音盲 2024-08-25 10:40:50

您还可以通过 FileInfo 检查 mime 类型,而不是使用扩展名。

You could also check the mime-type thanks to FileInfo rather than using the extension.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文