php - 使用 PHP 压缩和缓存 CSS

标签 php html css caching compression

我目前正在尝试为我的 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";
        } 
    }
}
?>

最佳答案

您缺少 rel="stylesheet"来自您的 <link> 的属性标签。除此之外,代码看起来还不错。

您可能还希望查看问答 here .

关于php - 使用 PHP 压缩和缓存 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11834976/

相关文章:

html - 有没有办法直接在css后台使用图片数据?

css - 您如何缩小内容以适合 div?

css - 如何让嵌套的 div 在缩放时随父级一起移动

css - 如何将图像背景添加到不透明的文本?

Php Mysql 开关/案例声明

JavaScript 文本节点属性

php - 如何检查对象是否是特定类的实例?

CSS3 : right angled triangle with bow/arc

javascript - Laravel + AngularJs,使用 ng-scr 的基本路径而不是当前路径

php - php 只显示最近 5 天的记录