Output Buffering (OB) 在 PHP 腳本與 SAPI(Apache/FPM/CLI)之間插入一層緩衝區:
echo/print 等輸出不再直接發送給客戶端,而是暫存於 PHP 內部緩衝區header()/setcookie()/session_start() 等「發送 Header」操作直接寫入 SAPI 緩衝區(不受 OB 影響)ob_end_flush() 時,OB 內容被推送到 SAPI 緩衝區,最後一次性發送給瀏覽器關鍵區別:OB 是 PHP 層面的緩衝;flush() 則是刷新 SAPI/Web Server 層緩衝。正確順序:ob_flush() → flush()。
| 場景 | 說明 | 典型代碼 |
|---|---|---|
| 解決「Header already sent」 | 在輸出內容前開啟 OB,Header 可隨時發送 | ob_start(); echo '...'; header('Location: ...'); ob_end_flush(); |
| 捕獲不可返回的輸出 | phpinfo()、var_dump()、模板引擎輸出等 | ob_start(); phpinfo(); $info = ob_get_clean(); |
| 輸出後處理 | GZIP 壓縮、字符替換、編碼轉換、XSS 過濾 | ob_start('ob_gzhandler'); 或自定義 callback |
| 靜態頁生成/全頁緩存 | 捕獲完整 HTML 寫入檔案或 Redis | $html = ob_get_contents(); file_put_contents('page.html', $html); |
| 函數 | 行為 | 返回值 | 是否關閉 OB |
|---|---|---|---|
ob_start([callback]) | 開啟新緩衝區(可巢狀) | bool | 否 |
ob_clean() | 清空當前緩衝區內容 | void | 否 |
ob_end_clean() | 清空並關閉當前緩衝區 | bool | 是 |
ob_get_clean() | 取得內容、清空、關閉 | string | 是 |
ob_flush() | 輸出內容到上層、清空當前 | bool | 否 |
ob_end_flush() | 輸出內容到上層、清空、關閉 | bool | 是 |
ob_get_flush() | 取得內容、輸出到上層、清空、關閉 | string | 是 |
ob_get_contents() | 取得當前緩衝區內容(不清空) | string/false | 否 |
ob_get_level() | 當前巢狀層級 | int | — |
ob_implicit_flush([true]) | 開啟/關閉隱式刷新(每次 echo 即 flush) | void | — |
<?php
ob_start('ob_gzhandler'); // 自動檢測瀏覽器 Accept-Encoding
// 你的業務邏輯...
ob_end_flush();
<?php
ob_start();
/* 業務邏輯 */
$content = ob_get_contents();
ob_end_clean();
$encoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
if (strpos($encoding, 'gzip') !== false) {
header('Content-Encoding: gzip');
echo gzencode($content, 6); // 壓縮等級 1-9
} else {
echo $content;
}
| 指令 | 預設 | 說明 |
|---|---|---|
output_buffering | 4096 (PHP 7+) | On/數值:全腳本自動開啟 OB,數值為緩衝區大小(位元組),達上限自動 flush |
output_handler | 空 | 全域輸出處理器,如 mb_output_handler、ob_gzhandler |
implicit_flush | Off | 等同 ob_implicit_flush(true) |
ob_start() 必須配對 ob_end_flush() 或 ob_end_clean(),否則導致內容重複輸出或 Header 錯誤。用 ob_get_level() 調試。ob_flush() 與 flush():
// 正確:先刷 PHP 緩衝,再刷 WebServer 緩衝
ob_flush();
flush();
ob_flush() + flush() 邊產生邊輸出,或直接用 fwrite(STDOUT, ...) 繞過 OB。<?php
set_time_limit(0);
ini_set('memory_limit', '64M');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="export.csv"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
// 開啟隱式刷新,或手動控制
ob_implicit_flush(true);
ob_end_flush(); // 關閉預設 OB(若 php.ini output_buffering=On)
$fp = fopen('php://output', 'w');
// UTF-8 BOM 讓 Excel 正確識別
fwrite($fp, "\xEF\xBB\xBF");
fputcsv($fp, ['ID', '姓名', '郵箱', '註冊時間']);
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$stmt = $pdo->query('SELECT id, name, email, created_at FROM users');
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
fputcsv($fp, $row);
}
fclose($fp);
結語:OB 是把雙刃劍。用對了能優雅解決 Header 衝突、實現緩存/壓縮/靜態化;濫用則增加記憶體壓力、掩蓋架構問題。原則:只在需要「攔截輸出」的地方精準開啟,用完即關,避免全域長期開啟。