【问题标题】:PHP - compress static css file with GZIPPHP - 使用 GZIP 压缩静态 css 文件
【发布时间】:2010-09-23 20:19:41
【问题描述】:

所以我有一个 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 脚本与样式表移动到同一目录中的情况下解决此问题吗?

【问题讨论】:

  • 对于阅读本文的人:不要使用来自 OP 的代码!该代码不验证文件路径,有人可以下载整个网站,包括 PHP 文件或运行 Web 服务器的用户有权访问的任何文件。

标签: php html css compression gzip


【解决方案1】:

如果你的网络服务器有这样的功能,你可以使用 URL 重写来保持整洁。

一个 mod_rewrite 的例子:

RewriteRule ^images/style\.css$ lib/c.php?css=../style.css

那么,你可以简单地:

@import "http://mysite.com/images/style.css";

我还建议您再看一下您的脚本。如果我加载此 URL 会发生什么?

http://mysite.com/lib/c.php?css=.htpasswd

【讨论】:

  • 谢谢,我添加了文件扩展名检查(如果是 css 或 js 则更进一步)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 2013-05-10
  • 2011-05-10
  • 1970-01-01
  • 2019-07-03
  • 2011-10-11
  • 1970-01-01
相关资源
最近更新 更多