Fixing "Cannot modify header information - headers already sent" in PHP
The warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.
On this page
Warning: Cannot modify header information - headers already sent by (output started at /var/www/app/config.php:12) in /var/www/app/login.php on line 30
HTTP headers must be sent before the body. As soon as PHP outputs a single byte, it sends the headers, and any later header(), setcookie(), session_start() or redirect fails. The message tells you both places: where output started, and where you tried to send a header.
Step 1: go to “output started at”
Open the file and line in the parentheses (config.php:12 above). That is the bug. The line in login.php is just the first victim.
The five usual culprits
1. Whitespace or HTML before <?php. A blank line or a space before the opening tag is output.
2. A UTF-8 byte order mark. Some editors add three invisible bytes (EF BB BF) at the start of a file. The warning points at line 1. Check and strip it:
head -c3 config.php | xxd # efbb bf = BOM
sed -i '1s/^\xEF\xBB\xBF//' config.php
3. A closing ?> followed by a newline. In files that contain only PHP, leave out the closing tag entirely. PSR-12 and PER Coding Style require this.
4. echo, print, var_dump() or print_r() left in from debugging, including inside an included file.
5. A warning or deprecation printed to the page. With display_errors=On, a notice such as “Deprecated: Passing null to parameter” is itself output. After a PHP upgrade, this is the most common cause. Fix the notice, and set display_errors=Off in production (log errors instead).
Fixes that solve it
- Move logic before output: do redirects, cookies and
session_start()at the top of the request, before rendering templates. - Exit after redirecting:
header('Location: /dashboard/', true, 303);
exit;
- Use a framework’s response object (Symfony
Response, Laravelredirect()), which collects headers and body and sends them in the right order. - You can check from code:
if (headers_sent($file, $line)) { error_log("Output started at $file:$line"); }.
About output buffering
ob_start() at the top of the script, or output_buffering=4096 in php.ini, holds output in memory so headers can still be sent later. It hides the symptom and can be a sensible safety net, but find the stray output anyway: a BOM or warning is still corrupting responses such as JSON or file downloads.