PHP - 使用 GZIP 压缩静态 css 文件
所以我有一个CSS文件,style.css。在同一目录中我有 images/ 文件夹。 如何制作一个压缩 style.css 的脚本,但来自另一个文件夹?
现在我有这个:
<?php
if(isset($_GET['css'])) $file = array('url' => htmlspecialchars($_GET['css']), 'type' => 'text/css');
if(isset($_GET['js'])) $file = array('url' => htmlspecialchars($_GET['js']), 'type' => 'application/javascript');
if(!isset($file)) exit();
header('Content-type: '.$file['type']);
header('Cache-Control: max-age='.(60*60*6).', must-revalidate');
// whitespace+comment removal, in case gzip is off
function compress($buffer){
global $file;
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), ' ', $buffer);
return $buffer;
}
if(extension_loaded('zlib'))
if(substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");
else ob_start("compress");
include($file['url']);
ob_end_flush();
?>
并像这样使用它:
<style type="text/css">
@import "http://mysite.com/lib/c.php?css=../style.css";
</style>
一切都很好,除了 css 文件内图像的路径不再起作用。 我认为这是因为 (images/bg.jpg) 变成 (../images/bg.jpg)
我可以解决这个问题,而不必将我的 c.php 脚本移动到与样式表相同的目录中吗?
so I have a css file, style.css. in the same directory I have the images/ folder.
How can I make a script that compresses style.css, but from another folder?
Right now I have this:
<?php
if(isset($_GET['css'])) $file = array('url' => htmlspecialchars($_GET['css']), 'type' => 'text/css');
if(isset($_GET['js'])) $file = array('url' => htmlspecialchars($_GET['js']), 'type' => 'application/javascript');
if(!isset($file)) exit();
header('Content-type: '.$file['type']);
header('Cache-Control: max-age='.(60*60*6).', must-revalidate');
// whitespace+comment removal, in case gzip is off
function compress($buffer){
global $file;
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), ' ', $buffer);
return $buffer;
}
if(extension_loaded('zlib'))
if(substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");
else ob_start("compress");
include($file['url']);
ob_end_flush();
?>
and use it something like this:
<style type="text/css">
@import "http://mysite.com/lib/c.php?css=../style.css";
</style>
everything is ok except that the path to the images inside the css file don't work anymore.
i think it's because (images/bg.jpg) becomes (../images/bg.jpg)
can i fix this without having to move my c.php script in the same directory as the stylesheet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的网络服务器有这样的功能,您可以使用 URL 重写来保持整洁。
mod_rewrite 的示例:
然后,您可以简单地:
我还建议您再看一下您的脚本。如果我加载此 URL 会发生什么?
If your web server has such feature, you can use URL rewriting to keep things tidy.
An example with mod_rewrite:
Then, you can simply:
I also recommend you give a second look to your script. What happens if I load this URL?