Last updated on June 24th, 2025 at 10:24 am
Encountering the dreaded “Cannot modify header information – headers already sent by” warning in PHP? You’re not alone — this is one of the most common PHP headaches. Let’s unpack why it happens and walk through foolproof steps to fix it.
What’s Actually Going On?
PHP sends HTTP headers (like redirects or cookies) only once, before any content is shown. If any output (HTML, echo, whitespace) reaches the browser first, PHP can’t modify headers after that—you’ll see a message like:
Cannot modify header information - headers already sent by (output started at /path/to/file.php:25)
This warning tells you:
- Which file and line produced the first output
- Where the failing
header()call happened afterward
💥 Common Causes of the Error
- Echo/print/HTML tags before header calls
- Whitespace or blank lines before
<?phpor after?> - UTF-8 BOM hidden characters at the start of a file
- Premature output from debugging statements like
var_dump(),print_r(), or error traces
🛠️Step-by-Step Fixes
1. Move header() Before Any Output
Keep all header logic at the very top of your PHP files—before any HTML or echo statements.
Example structure:
<?php
// PHP logic & header() here
header('Location: dashboard.php');
exit;
?>
<!-- Only HTML here -->
This practice cleanly separates policy logic from presentation
2. Remove Leading/Trailing Whitespace
Ensure no extra spaces or line breaks:
- Before the opening
<?phptag - After a closing
?>tag
Better yet, omit the closing?>in pure PHP files to avoid this altogether
3. Eliminate Hidden BOM Characters
If using UTF-8 without BOM, re-save your files without BOM using a plain text editor (VS Code, Sublime, Notepad++). Even invisible BOM bytes can trigger unwanted output .
4. Use headers_sent() to Diagnose
Add this snippet before your headers to debug:
if (headers_sent($file, $line)) {
die("Headers already sent by $file on line $line");
}
header('Location: account.php');
exit;
This reveals exactly where output began
5. Consider Output Buffering (Optional)
Temporarily use output buffering—but don’t rely on it long-term:
<?php
ob_start();
// your logic here
header('Location: home.php');
exit;
ob_end_flush();
?>
While it hides the problem, it’s better to fix the cause rather than masking it
Quick Fix Checklist
header()is the very first thing after<?php- No whitespace before
<?phpor after?> - UTF‑8 encoding without BOM
- No accidental
echo,print, or debugging output - Tested with
headers_sent()if redirect still fails
Why It Matters
Ignoring this error can prevent redirects, cookie setting, session management—and can quietly ruin your website flow. Fixing it ensures you’ll avoid broken redirects, security issues, and lost functionality.
TL;DR
Keep PHP logic above presentation, strip invisible characters, and only plan output after setting headers. Your redirects and cookies will work flawlessly again.
cool….