[Solved-5 Solutions] How to fix “Headers already sent” error in PHP
Error Description:
- When running the script, we get several errors like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
- The lines mentioned in the error messages contain
header()
andsetcookie()
calls. - What could be the reason for this? And how to fix it?
Solution 1:
- Functions that send/modify HTTP headers must be invoked before any output is made.
summary ?
Otherwise the call fails:
Warning: Cannot modify header information - headers already sent (output started at script:line)
- Some functions modifying the HTTP header are:
- header / header_remove
- session_start / session_regenerate_id
- setcookie / setrawcookie
Output can be:
- Unintentional:
- Whitespace before <?php or after ?>
- The UTF-8 Byte Order Mark specifically
- Previous error messages or notices
- Intentional:
print, echo
and other functions producing output- Raw
<html>
sections prior<?php
.
Solution 2:
- This error message gets triggered when anything is sent before we send HTTP headers (with
setcookie
orheader
). Common reasons for outputting something before the HTTP headers are: - Accidental whitespace, often at the beginning or end of files, like this:
- To avoid this, simply leave out the closing ?> - it's not required anyways.
- Byte order marks at the beginning of a php file. Examine the php files with a hex editor to find out whether that's the case. They should start with the bytes 3F 3C. We can safely remove the BOM EF BB BF from the start of files.
- Explicit output, such as calls to
echo, printf, readfile, passthru
, code before <? etc. - A warning outputted by php, if the display_errors php.ini property is set. Instead of crashing on a programmer mistake, php silently fixes the error and emits a warning. While we can modify the display_errors or error_reporting configurations, we should rather fix the problem.
- Common reasons are accesses to undefined elements of an array (such as
$_POST['input']
without using empty or isset to test whether the input is set), or using an undefined constant instead of a string literal (as in $_POST[input], note the missing quotes). - Turning on output buffering should make the problem go away; all output after the call to
ob_start
is buffered in memory until you release the buffer, e.g. withob_end_flush
- However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header.
Solution 3:
- Instead of the below line
- We must write
- or
Solution 4:
- It is because of this line:
- We should not print/echo anything before sending the headers.
Solution 5:
- Use
- At the very top of your script, and
- At the bottom of your script. This will turn output buffering on and the headers will be created after the page is buffered.