How to Solve “Headers already sent” error in PHP

This Warning is shown by PHP when you use the header function to output headers or use the setcookie function to set cookies after any echo or content which is not inside the PHP tag.

We need to make sure functions that send or modify HTTP headers must be invoked before any output is made.

Why Error Occured

PHP scripts generate HTML content and send HTTP/CGI headers to the webserver. The headers always come first on the page/output. The headers must be passed to the webserver before PHP can do anything else.

The PHP will flush all gathered headers once it receives the first output (print, echo, html>). Following that, it is free to transmit whatever output it desires. It is, however, unable to send any more HTTP headers at that point.

You’ll get errors like the below:

Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:2) in /some/file.php on line 12

Line no 12 contain header() and setcookie() calls.

PHP Methods that modify the HTTP header

There are some functions modifying the HTTP header:

How To Generate Error

You can generate error(header already sent) as like below PHP code:

<?php
echo "Hello World";
header("Location: /redirect.php");
?>

How To Solve: Cannot modify header information

You can utilize output buffering functions to automatically buffer your output before sending it, and the output will be sent in chunks at the end.

The functions that send/modify HTTP headers must be invoked before any output is made. Otherwise, the call fails:

<?php
ob_start(); ?>  
Hello World !!!   
<?php
setcookie("name","value",100);   
?>  
Again !!!  
<?php  
ob_end_flush();  
?>

Some Other Reasons to generate Errors

  • Whitespace before <?php or after ?>
  • The UTF-8 Byte Order Mark specifically
  • Previous error messages or notices
  • print, echo and other functions producing output
  • Raw <HTML> sections prior <?php code.

Leave a Reply

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