PHP error guide
PHP "Cannot modify header information: headers already sent"
Error summary
Something printed output before `header()`, `setcookie()`, or `session_start()`. Find the first output—often a UTF-8 BOM, whitespace before `<?php`, or an early `echo`.
What it means
Something printed output before header(), setcookie(), or session_start(). Find the first output—often a UTF-8 BOM, whitespace before <?php, or an early echo.
What the error means
HTTP headers must be sent before the body. Once any body bytes are emitted, PHP cannot change headers for that response.
Why PHP produces it
The SAPI flushes headers when the first body output occurs. Later header APIs warn and leave cookies/redirects ineffective.
PHP version notes
Same class of failure affects session_start() and setcookie().
Most common causes
- Whitespace or BOM before
<?php - Early
echo/print/HTML outside PHP - Warnings printed before session/header calls
- Included files that close
?>and trail whitespace
Minimal examples
BAD — reproduces the problem
?>\n<!-- accidental output -->\n<?php\nheader('Location: /');\n
FIXED — safer pattern
<?php\nheader('Location: /');\nexit;
Step-by-step diagnosis
- Read the “output started at file:line” portion of the warning.
- Open that file in a hex-aware editor and check for BOM (
EF BB BF). - Ensure pure-PHP files omit the closing
?>. - Temporarily enable output buffering only as a diagnostic, not a permanent mask.
Fixes
Fix #1: Remove premature output
Delete BOM/whitespace and move headers before any HTML.
<?php\ndeclare(strict_types=1);\n\nsession_start();\nheader('Content-Type: application/json');\n\necho json_encode(['ok' => true]);
Fix #2: Restructure redirects
Compute redirects before rendering templates.
<?php\nif (!$auth->check()) {\n header('Location: /login/', true, 302);\n exit;\n}\nrequire 'layout.php';
Common mistakes when fixing it
- Using
@header()to hide the warning without fixing output order - Leaving
display_errorson in production so warnings become the first output
How to prevent it
- PSR-7 style response objects that delay emission
- Never close
?>in pure PHP files - Save PHP sources as UTF-8 without BOM
Web server / environment notes
Web SAPIs; less relevant for pure CLI unless headers emulated
Tags: fpm,apache,nginx,wordpress
Categories
Related PHP errors
-
Cannot modify header information — headers already sent
Warning: Cannot modify header information - headers already sent by (output started at %s:%d) in %s on line %d -
Cannot send session cache limiter or cookie
Warning: session_start(): Cannot send session %s - headers already sent -
session_start cannot run after output
Warning: session_start(): Session cannot be started after headers have already been sent