使用PHP压缩和缓存CSS

7

我目前正在尝试为我的CSS文件实现一种压缩方法。我基本上是按照和JS文件相同的方式来操作,但是却无法工作。我通过Firebug工具进行了检查,但是没有CSS被加载。

我该如何调用css.php,然后再调用已经压缩过的CSS文件呢?

以下是与JS文件一起工作的代码,文件名为scripts.php(我没有指定.js扩展名):

<script type="text/javascript" src="js/scripts.php?build=123&load=foo,bar"></script>

我想对我的CSS文件执行同样的操作:

<link href="styles/css.php?build=123&load=foo,bar/jquery-ui-1.8rc2.custom" type="text/css">

css.php应该进行压缩:

<?php
error_reporting(E_ERROR);
// see http://web.archive.org/web/20071211140719/http://www.w3.org/2005/MWI/BPWG/techs/CachingWithPhp
// $lastModifiedDate must be a GMT Unix Timestamp
// You can use gmmktime(...) to get such a timestamp
// getlastmod() also provides this kind of timestamp for the last
// modification date of the PHP file itself

function cacheHeaders($lastModifiedDate) {
    if ($lastModifiedDate) {
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModifiedDate) {
            if (php_sapi_name()=='CGI') {
                Header("Status: 304 Not Modified");
            } else {
                Header("HTTP/1.0 304 Not Modified");
            }
            exit;
        } else {
            $gmtDate = gmdate("D, d M Y H:i:s \G\M\T",$lastModifiedDate);
            header('Last-Modified: '.$gmtDate);
        }
    }
}

// This function uses a static variable to track the most recent
// last modification time
function lastModificationTime($time=0) {
    static $last_mod ;
    if (!isset($last_mod) || $time > $last_mod) {
        $last_mod = $time ;
    }
    return $last_mod ;
}

lastModificationTime(filemtime(__FILE__));
cacheHeaders(lastModificationTime());
header("Content-type: text/css; charset: UTF-8");

ob_start ("ob_gzhandler");

foreach (explode(",", $_GET['load']) as $value) {
    if (is_file("$value.css")) {
        $real_path = mb_strtolower(realpath("$value.css"));
        if (strpos($real_path, mb_strtolower(dirname(__FILE__))) !== false ||strpos($real_path, mb_strtolower(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR)) !== false) {
            lastModificationTime(filemtime("$value.css"));
            include("$value.css"); echo "\n";
        } 
    }
}
?>
2个回答

2
您的 <link> 标签缺少 rel="stylesheet" 属性。除此之外,代码看起来还不错。
您可能还希望查看这里的问题和答案:here

1

尝试使用minify。这个类可以压缩和缓存js和css。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接