萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Firefox「內容編碼錯誤」與 IE「頁面無法顯示」:ob_gzhandler 輸出衝突排查

錯誤現象

  • Firefox:內容編碼錯誤 — 無法顯示頁面,因為使用了無效或不支援的壓縮格式
  • Chrome/Edge:ERR_CONTENT_DECODING_FAILED
  • IE:該頁無法顯示
  • curl 測試:curl -I -H "Accept-Encoding: gzip" url 回傳亂碼或截斷

根本原因

ob_start('ob_gzhandler') 在 已有輸出內容 (echo、空白、BOM、include 檔案輸出) 後被呼叫,導致壓縮流损坏,瀏覽器解壓失敗。

排查步驟

  1. 檢查 php.ini:output_buffering = 4096 (開啟可容忍少量前置輸出)
  2. 檢查入口檔:<?php 前無空白、BOM、HTML 註解
  3. 檢查 include/require 檔案:結尾無 ?> 後的換行/空白 (建議純 PHP 檔省略結尾標籤)
  4. 檢查框架啟動流程:框架可能在 bootstrap 階段已有輸出

解決方案

方案 A:移除 ob_gzhandler,改用 Web 伺服器壓縮 (推薦)

# 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 輸出衝突。

方案 B:修正 PHP 端輸出順序

<?php
// 入口檔最頂端
ob_start(); // 先開啟緩衝,不指定 callback

// 或有條件啟用 gzip
if (function_exists('ob_gzhandler') && !headers_sent()) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}

// ... 業務邏輯 ...

// 結束時自動 flush (或手動 ob_end_flush())
?>

方案 C:在 include 前後控制緩衝

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

最佳實踐總結

  • ✅ 由 Nginx/Apache 處理靜態/動態內容壓縮
  • ✅ PHP 專注業務邏輯,不處理傳輸層壓縮
  • ✅ 入口檔 ob_start() 統一緩衝,避免過早輸出
  • ✅ 純 PHP 類別檔案 省略結尾 ?>
  • ✅ 使用 php-cs-fixer / phpcs 自動修正編碼/空白問題
copyright © 萬盛學電腦網 all rights reserved