0
0
PhpDebug / FixBeginner · 4 min read

How to Fix 'Headers Already Sent' Error in PHP Quickly

The headers already sent error in PHP happens when output is sent before calling functions like header(). To fix it, remove any output (including spaces or new lines) before header() calls or use output buffering with ob_start().
🔍

Why This Happens

This error occurs because PHP sends HTTP headers automatically before any output. If your script sends any output (like HTML, spaces, or even blank lines) before calling header(), PHP cannot modify headers and throws this error.

php
<?php
// Output sent before header()
echo "Hello!";
header('Location: http://example.com');
?>
Output
Warning: Cannot modify header information - headers already sent by (output started at /path/to/script.php:2) in /path/to/script.php on line 3
🔧

The Fix

To fix this, ensure no output is sent before header(). Remove any echo, spaces, or blank lines before the header call. Alternatively, start output buffering with ob_start() at the top to delay output until headers are sent.

php
<?php
// Correct: no output before header
header('Location: http://example.com');
exit;

// Or use output buffering
// ob_start();
// echo "Hello!";
// header('Location: http://example.com');
// ob_end_flush();
?>
🛡️

Prevention

Always place header() calls before any HTML or output. Avoid closing PHP tags at the end of files to prevent accidental whitespace. Use output buffering if you need to send headers after some output. Use code editors that highlight trailing spaces and blank lines.

⚠️

Related Errors

Similar errors include Cannot modify header information caused by BOM (Byte Order Mark) in UTF-8 files or whitespace outside PHP tags. Fix these by saving files without BOM and trimming whitespace.

Key Takeaways

Never send output before calling header() functions in PHP.
Remove extra spaces or blank lines outside PHP tags to avoid accidental output.
Use output buffering (ob_start()) to control when output is sent.
Avoid closing PHP tags at the end of pure PHP files to prevent whitespace issues.
Check for BOM in UTF-8 files if headers errors persist.