How to Fix 'Cannot Modify Header' Error in PHP
The
Cannot modify header error in PHP happens because headers must be sent before any output. To fix it, ensure no output (like echo or whitespace) appears before calling header() functions.Why This Happens
PHP sends HTTP headers before the page content. If any output (even a space or newline) is sent before calling header(), PHP cannot change headers and throws this error.
php
<?php // Broken code example echo "Hello"; header('Location: https://example.com'); ?>
Output
Warning: Cannot modify header information - headers already sent by (output started at ... ) in script.php on line X
The Fix
Move all header() calls before any output. Avoid echo, print, or whitespace before headers. This lets PHP send headers correctly.
php
<?php header('Location: https://example.com'); exit(); // No output before header call ?>
Output
(Redirects user to https://example.com without error)
Prevention
Always call header() before any HTML or echo statements. Use exit() after redirects to stop script execution. Avoid closing PHP tags at the end of files to prevent accidental whitespace output.
- Check for whitespace before
<?phpor after?> - Use output buffering (
ob_start()) if needed - Use IDE or linters to detect accidental output
Related Errors
Other similar errors include:
- Headers already sent by: caused by output before headers.
- Cannot modify header information - session already started: happens if session_start() is called after output.
Fixes are similar: ensure no output before these functions.
Key Takeaways
Always call header() before any output or HTML.
Avoid whitespace or echo before header() calls.
Use exit() after header redirects to stop script.
Check for accidental output with linters or output buffering.
Do not close PHP files with ?> to prevent trailing whitespace.