How to Fix "Cannot Modify Header Information - Headers Already Sent" in PHP
Google AdSense In-Article Display Placement
Publisher ID: ca-pub-XXXXXXXXXXXXXXXX (Configured in config.php)The warning "Cannot modify header information - headers already sent by (output started at...)" occurs when a script attempts to send HTTP headers (header(), setcookie(), session_start()) after HTML, whitespace, or error text has already been dispatched to the browser.
Look at the exact file and line number reported after "output started at". If line 1 is reported, you have whitespace or an invisible UTF-8 BOM character before "<?php". Remove any echo, print, or blank lines before header() calls, or enable output buffering with ob_start() at the top of your bootstrap file.
📋 Guide Table of Contents
1. Problem Diagnosis & Symptoms
HTTP protocol specifies headers must be transmitted before the response body.
2. Primary Root Causes
- Cause: Accidental space or newline before the opening <?php tag.
- Cause: Invisible UTF-8 BOM byte sequence at the start of the file.
- Cause: Echo statements executed before session_start() or header("Location: ...").
3. Step-by-Step Diagnostic Fixes
Audit the Exact Output Trigger Line
Read the error: "output started at /app/config.php:1". Inspect line 1 of that specific file.
Implement Output Buffering
Add ob_start() at the beginning of your script:
<?php
ob_start();
session_start();
// Code that calls header() or setcookie()
ob_end_flush();
4. How to Verify the Resolution
- Refresh page and confirm headers send with 200/302 status.
5. Diagnostic Troubleshooting Matrix
| Symptom Observed | Root Cause | Recommended Action |
|---|---|---|
| Output started at line 1 in pure PHP file | UTF-8 BOM header or whitespace before <?php | Save file as UTF-8 without BOM and remove blank lines before <?php |
6. Critical Mistakes to Avoid
- ❌ Never rely solely on output buffering without fixing early echo statements.
7. Frequently Asked Questions
❓ Why does removing the closing ?> tag help?
PSR-12 recommends omitting ?> at the end of files to prevent accidental trailing newlines.
Official Technical References
Google AdSense In-Article Matched Content Unit