If you have encountered the PHP error “Cannot modify header information – headers already sent”, it means that there is a problem with the header code of your website page. Don’t worry, we’re here to help! In this article, we are going to see where the error came from and the corresponding solution.
Case 1: Using “echo” before the header
<?php echo "Welcome to StackHowTo"; ... header('Location: https://stackhowto.com/'); ?>
Remove “echo” before the header
<?php ob_start(); // PHP code ob_end_flush(); ?>
Case 2: Line break or spaces before <?php
Line breaks and spaces can be a problem. But there are also “invisible” character sequences that can cause this.
<?php ... header('Location: https://stackhowto.com/'); ?>
Delete everything before <?php
Case 3: BOM (Byte-Order-Mark) in PHP files encoded in utf-8
If you edited the PHP file with a text editor like Notepad and saved it, you may get the above error message. The reason is that utf-8 BOM (Byte-Order-Mark) added by some text editors, like for example Notepad. The PHP script should not have the “BOM”, because the “BOM” contains characters, which are sent before the header function.
ï»¿<?php ... header('Location: https://stackhowto.com/'); ?>
Change the encoding of the file to “without BOM” (eg using notepad++).
Or delete it using a HEX editor.
Case 4: Header Location is in a mixed PHP/HTML file
<html> ... <body> ... <?php header('Location: https://stackhowto.com/'); > ... </body> </html>
In this case, you cannot use Header Location, because the header and HTML code have already been sent!
Case 5: Lines, characters or blank spaces after ?> When using “include”
<?php echo "Welcome to StackHowto"; ?> ...
Delete everything after ?> In the included PHP file.