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

php
?>\n<!-- accidental output -->\n<?php\nheader('Location: /');\n

FIXED — safer pattern

php
<?php\nheader('Location: /');\nexit;

Step-by-step diagnosis

  1. Read the “output started at file:line” portion of the warning.
  2. Open that file in a hex-aware editor and check for BOM (EF BB BF).
  3. Ensure pure-PHP files omit the closing ?>.
  4. 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
<?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
<?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_errors on 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

Relevant ZendStudio.net tools