PHP项目如何配置静态资源压缩?

wen PHP项目 12

本文目录导读:

PHP项目如何配置静态资源压缩?

  1. 服务器级别压缩(推荐,性能最高)
  2. PHP 代码层面压缩
  3. 使用 PHP 缓存类管理压缩
  4. 结合 Webpack 或 Gulp 进行构建时压缩(推荐)
  5. 使用第三方库
  6. 最佳实践

在PHP项目中配置静态资源压缩,主要目的是为了加快页面加载速度,减少带宽消耗,以下是几种常见的配置方法,从服务器层面到代码层面,可以根据项目环境选择。

服务器级别压缩(推荐,性能最高)

Nginx 配置

在 Nginx 配置文件的 server 块或 location 块中添加:

# 开启 gzip 压缩
gzip on;
gzip_min_length 1k;    # 文件大于1KB才压缩
gzip_comp_level 6;     # 压缩级别 1-9,6是推荐平衡值
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml font/ttf font/opentype application/vnd.ms-fontobject;
gzip_vary on;
gzip_proxied any;
gzip_disable "msie6";
gzip_buffers 16 8k;
gzip_http_version 1.1;

Apache 配置

.htaccesshttpd.conf 中启用 mod_deflate

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml image/svg+xml
    # 排除浏览器
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    # 设置压缩级别
    DeflateCompressionLevel 6
    # 设置缓冲
    DeflateBufferSize 8192
</IfModule>

PHP 代码层面压缩

通用压缩函数

在 PHP 代码中通过 ob_gzhandler 实现:

<?php
/**
 * 开启输出压缩
 */
function enableCompression() {
    // 检测浏览器是否支持 gzip
    if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
        // 开启输出压缩,级别为6
        @ini_set('zlib.output_compression', 'On');
        @ini_set('zlib.output_compression_level', '6');
    }
}
// 在页面输出前调用
enableCompression();
// 或者使用 ob_gzhandler
ob_start('ob_gzhandler');
?>

针对静态资源的压缩

专门处理 CSS/JS 文件的压缩函数:

<?php
function compressStaticFile($filePath, $type = 'css') {
    $content = file_get_contents($filePath);
    if ($type === 'css') {
        // CSS 压缩:移除注释、空格、换行
        $content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
        $content = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $content);
        $content = preg_replace('/\s*([{}|:;,])\s+/', '$1', $content);
        $content = preg_replace('/\s+/', ' ', $content);
    } elseif ($type === 'js') {
        // JS 基础压缩(建议使用专业工具)
        $content = preg_replace('/\/\/[^\n]*/', '', $content);
        $content = preg_replace('/\/\*.*?\*\//s', '', $content);
        $content = str_replace(array("\r\n", "\r", "\n", "\t"), '', $content);
    }
    return $content;
}
// 使用示例
header('Content-Type: text/css');
echo compressStaticFile('/path/to/style.css', 'css');

使用 PHP 缓存类管理压缩

<?php
class StaticCompressor {
    private $cacheDir = '/tmp/static_cache/';
    private $compressLevel = 6;
    public function __construct() {
        if (!is_dir($this->cacheDir)) {
            mkdir($this->cacheDir, 0755, true);
        }
    }
    /**
     * 压缩并缓存静态文件
     */
    public function compress($filePath, $type) {
        $cacheKey = md5($filePath . filemtime($filePath));
        $cacheFile = $this->cacheDir . $cacheKey . '.' . $type . '.gz';
        // 检查缓存
        if (file_exists($cacheFile)) {
            return file_get_contents($cacheFile);
        }
        // 读取原文件
        $content = file_get_contents($filePath);
        // 根据类型压缩
        if ($type === 'css') {
            $content = $this->compressCSS($content);
        } elseif ($type === 'js') {
            $content = $this->compressJS($content);
        }
        // 压缩并缓存
        $compressed = gzencode($content, $this->compressLevel);
        file_put_contents($cacheFile, $compressed);
        return $compressed;
    }
    private function compressCSS($content) {
        $content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
        $content = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $content);
        return $content;
    }
    private function compressJS($content) {
        // 使用外部工具如 uglifyjs 或 terser
        // 此处简化处理
        return $content;
    }
    /**
     * 输出压缩后的静态资源
     */
    public function output($filePath, $type) {
        $content = $this->compress($filePath, $type);
        // 设置响应头
        header('Content-Encoding: gzip');
        header('Content-Type: ' . ($type === 'css' ? 'text/css' : 'application/javascript'));
        header('Content-Length: ' . strlen($content));
        header('Cache-Control: public, max-age=86400');
        header('Vary: Accept-Encoding');
        echo $content;
        exit;
    }
}
// 使用示例
$compressor = new StaticCompressor();
// 在路由中处理 /compress/css/style.css 请求
// $compressor->output('/path/to/style.css', 'css');
?>

结合 Webpack 或 Gulp 进行构建时压缩(推荐)

项目构建配置(package.json)

{
  "scripts": {
    "build": "webpack --mode production",
    "compress": "uglifyjs-folder js -o js.min --each '*.js' --pattern '**/*.js' && cleancss css/*.css -o css.min/"
  }
}

然后在 PHP 中调用构建后的压缩文件:

<?php
function loadCompressedAssets() {
    $manifest = json_decode(file_get_contents(__DIR__ . '/build/manifest.json'), true);
    return [
        'css' => $manifest['main.css'],
        'js'  => $manifest['main.js']
    ];
}
$assets = loadCompressedAssets();
echo '<link rel="stylesheet" href="' . $assets['css'] . '">';
echo '<script src="' . $assets['js'] . '"></script>';
?>

使用第三方库

Install via Composer

composer require matthiasmullie/minify

使用示例

<?php
use MatthiasMullie\Minify;
// CSS 压缩
$minifier = new Minify\CSS('/path/to/style.css');
$minifier->add('/path/to/other.css');
$minifier->minify('/path/to/output.css');
// JS 压缩
$minifier = new Minify\JS('/path/to/script.js');
$minifier->minify('/path/to/output.js');
// 在运行时压缩并输出
header('Content-Type: text/css');
$minifier = new Minify\CSS();
$minifier->add(file_get_contents('style1.css'));
$minifier->add(file_get_contents('style2.css'));
echo $minifier->minify();
?>

最佳实践

  1. 优先级:服务器层压缩(Nginx/Apache)> 构建工具压缩 > PHP代码压缩
  2. 缓存策略:使用适当的 HTTP 缓存头,减少重复压缩
  3. 监控:使用浏览器开发者工具的 Network 面板检查 Content-Encoding: gzip
  4. 测试:压缩后要对功能进行完整测试,特别是 JavaScript
  5. 安全:确保压缩工具不会引入安全漏洞,定期更新依赖

推荐方案:服务器级压缩 + 构建工具预压缩,这样既高效又稳定,PHP只需负责读取已压缩的文件即可。

抱歉,评论功能暂时关闭!