# 警告：session_start()：当标头已发送时无法启动会话

- **ID:** `php/session-header-already-sent-output-buffering`
- **领域:** php
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

在调用 session_start() 之前，输出（例如空白、HTML 或 BOM）已发送到浏览器，阻止 PHP 设置会话 cookie 或标头。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PHP 8.1.0 | active | — | — |
| PHP 8.2.0 | active | — | — |
| PHP 8.3.0 | active | — | — |

## 解决方案

1. ```
   在 php.ini 中启用输出缓冲：
output_buffering = 4096
这会缓冲所有输出直到脚本结束，允许稍后发送标头。
   ```
2. ```
   删除所有包含文件中 <?php 之前的任何空白或 BOM，并确保在任何 echo 或 HTML 之前调用 session_start()：
<?php
session_start();
// 其余代码
?>
   ```

## 无效尝试

- **Adding ob_start() at the top of every script to buffer output** — This masks the issue and can cause memory bloat; it doesn't fix the root cause of premature output. (75% 失败率)
- **Moving session_start() to the very end of the file** — Session must be started before any output; moving it later will still fail if there is output before it. (90% 失败率)
