php

Warning: Cannot modify header information – headers already sent

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/');
?>

Solution:
Remove “echo” before the header
Use ob_start(); and ob_end_flush();.
 

 
Example:

<?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/');
?>

Solution:
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/');
?>

Solution:
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";
?>


...

Solution:
Delete everything after ?> In the included PHP file.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “Warning: Cannot modify header information – headers already sent

  • Chloé

    Hi,
    thank you for your article.
    In my part, the error msg is
    ” PHP Warning: Cannot modify header information – headers already sent by (output started at /home3/FWIO/public_html/modules/lgbannerhost/lgbannerhost.php:98) in /home3/FWIO/public_html/classes/controller/AdminController.php on line 1829 ”
    I was wondering if you could suggest a way to solve this error,
    Kind regards,
    Chloé

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *