curl -I -H "Accept-Encoding: gzip" url 回傳亂碼或截斷ob_start('ob_gzhandler') 在 已有輸出內容 (echo、空白、BOM、include 檔案輸出) 後被呼叫,導致壓縮流损坏,瀏覽器解壓失敗。
output_buffering = 4096 (開啟可容忍少量前置輸出)<?php 前無空白、BOM、HTML 註解?> 後的換行/空白 (建議純 PHP 檔省略結尾標籤)# Nginx gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_min_length 1000;
# Apache (mod_deflate)AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
優點:效能更好、不佔用 PHP 進程記憶體、支援靜態資源、避免 PHP 輸出衝突。
<?php
// 入口檔最頂端
ob_start(); // 先開啟緩衝,不指定 callback
// 或有條件啟用 gzip
if (function_exists('ob_gzhandler') && !headers_sent()) {
ob_start('ob_gzhandler');
} else {
ob_start();
}
// ... 業務邏輯 ...
// 結束時自動 flush (或手動 ob_end_flush())
?>
ob_start(); // 外層緩衝
include 'header.php'; // 可能有輸出
$headerContent = ob_get_clean(); // 取得並清除
ob_start('ob_gzhandler'); // 內層啟用 gzip
// 主要內容生成
$mainContent = renderView();
ob_end_flush();
# 1. 檢查回應標頭 curl -I -H "Accept-Encoding: gzip, deflate" https://example.com/ # 應看到: Content-Encoding: gzip # 2. 檢查內容完整性 curl -H "Accept-Encoding: gzip" -s https://example.com/ | gunzip -c | head -20 # 3. 瀏覽器開發者工具 Network → Headers → Content-Encoding: gzip
ob_start() 統一緩衝,避免過早輸出?>php-cs-fixer / phpcs 自動修正編碼/空白問題