How to Fix 'Headers Already Sent' Error in PHP Quickly
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 // Output sent before header() echo "Hello!"; header('Location: http://example.com'); ?>
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 // 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.