PHP “Headers Already Sent” Issue
1. The Problem
PHP sends HTTP headers before any output. If output occurs first, functions that modify headers will fail:
Warning: Cannot modify header information – headers already sent (output started at script.php:52)
Functions affected
header() / header_remove()
session_start() / session_regenerate_id()
setcookie() / setrawcookie()
Possible sources of output
Unintentional:
Whitespace before
UTF-8 Byte Order Mark (BOM)
Previous error messages or notices
Intentional:
print, echo, var_dump(), printf()
Raw HTML outside PHP tags
2. Why it Happens
A typical HTTP response looks like this:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
……
Headers must be sent first.
When PHP encounters the first output, it flushes all collected headers.
Any subsequent attempt to modify headers (e.g., header()) will fail.
3. How to Locate Premature Output
The warning provides key information:
Warning: Cannot modify header information – headers already sent by (output started at /www/usr2345/htdocs/auth.php:52) in /www/usr2345/htdocs/index.php on line 100
Line 100: where header() failed.
Output started at auth.php:52: the actual source of premature output.
4. Typical Causes
a) Intentional Output
Functions producing output:
print, echo, printf, vprintf
trigger_error, var_dump, print_r
readfile, passthru, flush, imagepng, imagejpeg
Fix: Call header() or session_start() before any output.
b) Raw HTML
// Too late for headers already
Fix: Place processing and header logic at the top of the script.
Use templating to separate output from logic.
c) Leading or Trailing Whitespace
can also trigger the warning.
Fix: Remove whitespace around PHP tags. Ideally, omit the closing ?> in pure PHP files.
d) UTF-8 Byte Order Mark (BOM)
BOM bytes (EF BB BF) are treated as output by PHP.
Common in files saved by some graphical editors or IDEs.
Can appear as strange characters () in output.
Fix: Save files without BOM using a proper editor.
5. Best Practices to Avoid This Error
Place all header-related functions at the top of the script.
Separate logic and output using templates.
Avoid unnecessary closing PHP tags in pure PHP files.
Check for whitespace before .
Use editors that allow saving UTF-8 without BOM.
For debugging, enable output buffering:
ob_start(); // Start buffer
// Your script here
ob_end_flush(); // Send output