本文目录导读:

在 PHP 中实现 PageSpeed 优化,主要有以下几种方法:
使用 PageSpeed 模块(推荐)
Apache mod_pagespeed
# 安装(Ubuntu/Debian) apt-get install libapache2-mod-pagespeed # 启用模块 a2enmod pagespeed service apache2 restart
Nginx PageSpeed
# 安装 ngx_pagespeed
# 然后配置
location ~ \.php$ {
pagespeed on;
pagespeed RewriteLevel CoreFilters;
}
纯 PHP 实现的关键优化
CSS/JS 压缩和合并
<?php
class PageSpeedOptimizer {
// CSS 压缩
public static function minifyCSS($css) {
// Remove comments
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
// Remove whitespace
$css = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css);
return $css;
}
// JS 压缩(简单的实现)
public static function minifyJS($js) {
// Remove comments
$js = preg_replace('/(?:(?:\/\*(?:[^*]|\*+[^*\/])*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $js);
// Remove whitespace around tokens
return preg_replace('/[ \t]+/', ' ', $js);
}
// 合并 CSS 文件
public static function combineCSS($files) {
$combined = '';
foreach ($files as $file) {
$combined .= file_get_contents($file);
}
return self::minifyCSS($combined);
}
// 合并 JS 文件
public static function combineJS($files) {
$combined = '';
foreach ($files as $file) {
$combined .= file_get_contents($file) . ';';
}
return self::minifyJS($combined);
}
}
?>
HTML 压缩
<?php
class HTMLMinifier {
public static function minify($html) {
// 去掉注释
$html = preg_replace('/<!--(?!\[if)(.*?)-->/s', '', $html);
// 去掉多余空白
$html = preg_replace('/\s+/', ' ', $html);
// 去掉标签间的多余空格
$html = preg_replace('/>\s+</', '><', $html);
return trim($html);
}
// 缓冲输出
public static function start() {
ob_start();
}
public static function end() {
$html = ob_get_clean();
echo self::minify($html);
}
}
?>
图片优化
<?php
class ImageOptimizer {
// 调整图片大小
public static function resize($source, $maxWidth, $maxHeight) {
list($width, $height, $type) = getimagesize($source);
// 计算新尺寸
$ratio = min($maxWidth/$width, $maxHeight/$height);
$newWidth = $width * $ratio;
$newHeight = $height * $ratio;
// 创建新图片
$src = imagecreatefromstring(file_get_contents($source));
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// 输出
$output = '/path/to/cache/' . md5($source . $maxWidth . $maxHeight) . '.jpg';
imagejpeg($dst, $output, 80); // 80% 质量
imagedestroy($src);
imagedestroy($dst);
return $output;
}
// 转为 WebP 格式
public static function toWebP($source) {
if (function_exists('imagewebp')) {
$img = imagecreatefromstring(file_get_contents($source));
$output = str_replace(['.jpg', '.png'], '.webp', $source);
imagewebp($img, $output, 80);
imagedestroy($img);
return $output;
}
return $source;
}
}
?>
缓存机制
<?php
class CacheManager {
private static $cacheDir = '/cache/';
// 页面缓存
public static function pageCache($key, $ttl = 3600) {
$file = self::$cacheDir . md5($key) . '.html';
if (file_exists($file) && (time() - filemtime($file) < $ttl)) {
echo file_get_contents($file);
exit;
}
ob_start(function($html) use ($file) {
file_put_contents($file, $html);
return $html;
});
}
// 设置过期头
public static function setCacheHeaders($ttl = 3600) {
header('Cache-Control: max-age=' . $ttl);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $ttl) . ' GMT');
header('Pragma: cache');
}
// CDN 和压缩
public static function enableCompression() {
if (ob_get_level() == 0 && !ob_start('ob_gzhandler')) {
ob_start();
}
}
}
?>
数据库查询优化
<?php
class QueryOptimizer {
private $logs = [];
// 查询日志
public function logQuery($sql, $params = [], $executionTime) {
$this->logs[] = [
'sql' => $sql,
'time' => $executionTime,
'timestamp' => microtime(true)
];
// 记录慢查询
if ($executionTime > 0.5) {
// 记录到慢查询日志
error_log("Slow query: " . $sql . " (" . $executionTime . "s)");
}
}
// 查询缓存
public function cacheQuery($key, $query, $ttl = 3600) {
static $cache = [];
if (isset($cache[$key]) && (time() - $cache[$key]['time'] < $ttl)) {
return $cache[$key]['data'];
}
$result = $query();
$cache[$key] = [
'data' => $result,
'time' => time()
];
return $result;
}
// 批量查询优化
public function batchQuery($queries) {
// 使用事务提高效率
// 或者使用多查询
}
}
?>
异步加载实现
<?php
class AsyncLoader {
// 异步加载 CSS
public static function loadCSSAsync($url) {
return '<script>
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = "' . $url . '";
document.head.appendChild(link);
</script>';
}
// 异步加载 JS
public static function loadJSAsync($url) {
return '<script async src="' . $url . '"></script>';
}
// 延迟加载
public static function deferJS($script) {
return '<script defer>' . $script . '</script>';
}
// 预加载关键资源
public static function preload($url, $type) {
return '<link rel="preload" href="' . $url . '" as="' . $type . '">';
}
}
?>
使用示例
<?php
// 完整优化示例
class FullPageSpeed {
public function init() {
// 开始输出缓冲
ob_start();
// 启用 Gzip 压缩
if (extension_loaded('zlib')) {
ob_start('ob_gzhandler');
}
// 页面上运行优化
add_action('shutdown', [$this, 'optimizeOutput']);
}
public function optimizeOutput() {
$html = ob_get_clean();
// HTML 压缩
$html = HTMLMinifier::minify($html);
// 图片优化
$html = $this->optimizeImages($html);
// CSS/JS 优化
$html = $this->optimizeResources($html);
// 设置缓存头
CacheManager::setCacheHeaders();
echo $html;
}
private function optimizeImages($html) {
// 正则匹配图片并优化
preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/', $html, $matches);
foreach ($matches[1] as $src) {
// 优化逻辑
}
return $html;
}
private function optimizeResources($html) {
// 优化 CSS/JS 引用
return $html;
}
}
?>
性能监控
<?php
class PerformanceMonitor {
public static function startTimer($name) {
$_SESSION['timers'][$name] = microtime(true);
}
public static function endTimer($name) {
if (isset($_SESSION['timers'][$name])) {
$elapsed = microtime(true) - $_SESSION['timers'][$name];
unset($_SESSION['timers'][$name]);
// 记录到日志
error_log("Performance - {$name}: {$elapsed} seconds");
return $elapsed;
}
return 0;
}
public static function trackQuery($sql, $time) {
if ($time > 0.5) { // 500ms
error_log("Slow Query: " . $sql);
}
}
}
?>
最佳实践建议
-
优先使用 mod_pagespeed 或 ngx_pagespeed
性能更好,改动最小
-
分层优化
- 服务器级别:缓存、压缩
- 应用级别:PHP 优化
- 前端级别:资源优化
-
监控和测试
- 使用 Google PageSpeed Insights
- 监测核心 Web Vitals
- 持续优化
这些方法可以结合使用,根据你的服务器环境和具体需求选择合适的方案。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播