How to fix “Headers already sent” error in PHP
When running my script, I am getting 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()
and setcookie()
calls.
What could be the reason for this? And how to fix it?
php header
locked by Gordon Jun 24 '15 at 11:40
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
comments disabled on deleted / locked posts / reviews |
When running my script, I am getting 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()
and setcookie()
calls.
What could be the reason for this? And how to fix it?
php header
locked by Gordon Jun 24 '15 at 11:40
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
Make sure no text is outputted (ob_start
andob_end_clean()
may prove useful here). You could then set a cookie or session equal toob_get_contents()
and then useob_end_clean()
to clear the buffer.
– Jack Tuck
Apr 3 '14 at 20:16
Use thesafeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php
– heinkasner
Jul 24 '14 at 13:29
5
~~~~~~~~~~ Your file ENCODING should not beUTF-8
, butUTF-8 (Without BOM)
~~~~~~~~~~~
– T.Todua
Sep 19 '14 at 8:00
comments disabled on deleted / locked posts / reviews |
When running my script, I am getting 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()
and setcookie()
calls.
What could be the reason for this? And how to fix it?
php header
When running my script, I am getting 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()
and setcookie()
calls.
What could be the reason for this? And how to fix it?
php header
php header
edited Jan 16 '14 at 17:41
community wiki
16 revs, 8 users 46%
Moses89
locked by Gordon Jun 24 '15 at 11:40
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
locked by Gordon Jun 24 '15 at 11:40
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
Read more about locked posts here.
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
Make sure no text is outputted (ob_start
andob_end_clean()
may prove useful here). You could then set a cookie or session equal toob_get_contents()
and then useob_end_clean()
to clear the buffer.
– Jack Tuck
Apr 3 '14 at 20:16
Use thesafeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php
– heinkasner
Jul 24 '14 at 13:29
5
~~~~~~~~~~ Your file ENCODING should not beUTF-8
, butUTF-8 (Without BOM)
~~~~~~~~~~~
– T.Todua
Sep 19 '14 at 8:00
comments disabled on deleted / locked posts / reviews |
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
Make sure no text is outputted (ob_start
andob_end_clean()
may prove useful here). You could then set a cookie or session equal toob_get_contents()
and then useob_end_clean()
to clear the buffer.
– Jack Tuck
Apr 3 '14 at 20:16
Use thesafeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php
– heinkasner
Jul 24 '14 at 13:29
5
~~~~~~~~~~ Your file ENCODING should not beUTF-8
, butUTF-8 (Without BOM)
~~~~~~~~~~~
– T.Todua
Sep 19 '14 at 8:00
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
Make sure no text is outputted (
ob_start
and ob_end_clean()
may prove useful here). You could then set a cookie or session equal to ob_get_contents()
and then use ob_end_clean()
to clear the buffer.– Jack Tuck
Apr 3 '14 at 20:16
Make sure no text is outputted (
ob_start
and ob_end_clean()
may prove useful here). You could then set a cookie or session equal to ob_get_contents()
and then use ob_end_clean()
to clear the buffer.– Jack Tuck
Apr 3 '14 at 20:16
Use the
safeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php– heinkasner
Jul 24 '14 at 13:29
Use the
safeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php– heinkasner
Jul 24 '14 at 13:29
5
5
~~~~~~~~~~ Your file ENCODING should not be
UTF-8
, but UTF-8 (Without BOM)
~~~~~~~~~~~– T.Todua
Sep 19 '14 at 8:00
~~~~~~~~~~ Your file ENCODING should not be
UTF-8
, but UTF-8 (Without BOM)
~~~~~~~~~~~– T.Todua
Sep 19 '14 at 8:00
comments disabled on deleted / locked posts / reviews |
11 Answers
11
active
oldest
votes
No output before sending headers!
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
- Whitespace before
Intentional:
print
,echo
and other functions producing output- Raw
<html>
sections prior<?php
code.
Why does it happen?
To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
How can you find out where the premature output occured?
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Print, echo
Intentional output from
print
andecho
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensureheader()
calls occur before messages
are written out.
Functions that produce output include
print
,echo
,printf
,vprintf
trigger_error
,ob_flush
,ob_end_flush
,var_dump
,print_r
readfile
,passthru
,flush
,imagepng
,imagejpeg
among others and user-defined functions.
Raw HTML areas
Unparsed HTML sections in a
.php
file are direct output as well.
Script conditions that will trigger aheader()
call must be noted
before any raw<html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
- Place form processing code atop scripts.
- Use temporary string variables to defer messages.
- The actual output logic and intermixed HTML output should follow last.
Whitespace before
<?php
for "script.php line 1" warnings
If the warning refers to output in line
1
, then it's mostly
leading whitespace, text or HTML before the opening<?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't
compensate multiple newlines or tabs or spaces shifted into such gaps.
UTF-8 BOM
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequenceEF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its
presence. They don't visualize it (obliged by the Unicode standard).
Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systemshexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
or similar such nomenclature. Often newcomers otherwise resort to creating new
files and just copy&pasting the previous code back in.
Correction utilities
There are also automated tools to examine and rewrite text files
(sed
/awk
orrecode
).
For PHP specifically there's thephptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
Whitespace after
?>
If the error source is mentioned as behind the
closing?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing
?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonlyinclude()d
scripts are the culprit.)
Error source mentioned as "Unknown on line 0"
It's typically a PHP extension or php.ini setting if no error source
is concretized.
- It's occasionally the
gzip
stream encoding setting
or theob_gzhandler
. - But it could also be any doubly loaded
extension=
module
generating an implicit PHP startup/warning message.
- It's occasionally the
Preceding error messages
If another PHP statement or expression causes a warning message or
notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or@()
-
when either doesn't obstruct debugging later on.
No error message
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like
this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
Output buffering as workaround
PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.
The
output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to
ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if
<?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitatingob_clean()
as furher workaround.)The buffer is limited in size, and can easily overrun when left to defaults.
And that's not a rare occurence either, difficult to track down
when it happens.
Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.
See also the basic usage example
in the manual, and for more pros and cons:
- What is output buffering?
- Why use output buffering in PHP?
- Is using output buffering considered a bad practice?
- Use case for output buffering as the correct solution to "headers already sent"
But it worked on the other server!?
If you didn't get the headers warning before, then the output buffering
php.ini setting
has changed. It's likely unconfigured on the current/new server.
Checking with headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
HTML
<meta>
tag
If your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the
<head>
section.
Most browsers still accept it.
JavaScript redirect
As alternative a JavaScript redirect
can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the
<meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)
Why setcookie()
and session_start()
are also affected
Both setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)
Further links
- Google provides a lengthy list of similar discussions.
- And of course many specific cases have been covered on Stack Overflow as well.
- The Wordpress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
- Adobe Community: PHP development: why redirects don't work (headers already sent)
- Nucleus FAQ: What does "page headers already sent" mean?
- One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link).
It covers HTTP in detail and gives a few guidelines for rewriting scripts.
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
Removing the closing?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
|
show 9 more comments
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes3F 3C
. You can safely remove the BOMEF 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 you can modify thedisplay_errors
or error_reporting configurations, you should rather fix the problem.
Common reasons are accesses to undefined elements of an array (such as$_POST['input']
without usingempty
orisset
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. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
add a comment |
I got this error many times before.and I am sure all PHP programmer at-least once got this error.
To solve this error you can solve use solution as per your problem level:
Possible Solution 1:
You may have left blank spaces before or after (at the end of file after ?> ) i.e.
THERE SHOULD BE NO BLANK SPACES HERE
<?php
echo "your code here";
?>
DO CHECK FOR BLANK SPACES HERE AS WELL; THIS LINE (blank line) SHOULD NOT EXIST.
Most of the time this should solve your problem.Do check all files associated with file you require
.
Note: Sometimes EDITOR(IDE) like gedit(a default linux editor) add one blank line on save save file.This should not happen. If you are using linux. you can use VI editor to remove space/lines after ?> at the end of the page.
If this is not your case then,then you can use ob_start for output buffering like below:
Possible Solution 2:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
17
ob_start()
just hides the problem; don't use it to solve this particular problem.
– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use ofob_start()
, then what should I do for solving this problem:Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
ob_start()
doesn't "hide" the problem, it solves the problem.
– TMS
Oct 22 '15 at 20:51
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
|
show 2 more comments
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
add a comment |
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
add a comment |
It is because of this line:
printf ("Hi %s,</br />", $name);
You should not print/echo anything before sending the headers.
add a comment |
COMMON PROBLEMS:
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
add a comment |
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
add a comment |
Another bad practice can invoke this problem which is not stated yet.
See this code snippet:
<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>
Things are okay,right?
What if "a_important_file.php" is this:
<?php
//some php code
//another line of php code
//no line above is generating any output
?>
----------This is the end of the an_important_file-------------------
This will not work? Why?Because already a new line is generated.
Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.
From PSR-2 2.2 :
- All PHP files MUST use the
Unix LF (linefeed) line ending
. - All PHP files MUST end with a
single blank line
. - The closing ?> tag MUST be
omitted
from files containingonly php
Believe me , following thse standards can save you a hell lot of hours from your life :)
2
According to several standards (Zend for example), you shouldn't put the closing?>
tag in any file in any case any way
– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except theCR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that hasLF
(Linux end of line) instead ofCR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN
– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between?>
<?php
, removing and adding single blank line, added and omitted closing tag?>
. In Windows+ Wamp all those combinations work fine. Wierd...
– Junior M
Jun 11 '15 at 14:13
|
show 1 more comment
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
add a comment |
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
add a comment |
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
No output before sending headers!
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
- Whitespace before
Intentional:
print
,echo
and other functions producing output- Raw
<html>
sections prior<?php
code.
Why does it happen?
To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
How can you find out where the premature output occured?
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Print, echo
Intentional output from
print
andecho
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensureheader()
calls occur before messages
are written out.
Functions that produce output include
print
,echo
,printf
,vprintf
trigger_error
,ob_flush
,ob_end_flush
,var_dump
,print_r
readfile
,passthru
,flush
,imagepng
,imagejpeg
among others and user-defined functions.
Raw HTML areas
Unparsed HTML sections in a
.php
file are direct output as well.
Script conditions that will trigger aheader()
call must be noted
before any raw<html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
- Place form processing code atop scripts.
- Use temporary string variables to defer messages.
- The actual output logic and intermixed HTML output should follow last.
Whitespace before
<?php
for "script.php line 1" warnings
If the warning refers to output in line
1
, then it's mostly
leading whitespace, text or HTML before the opening<?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't
compensate multiple newlines or tabs or spaces shifted into such gaps.
UTF-8 BOM
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequenceEF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its
presence. They don't visualize it (obliged by the Unicode standard).
Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systemshexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
or similar such nomenclature. Often newcomers otherwise resort to creating new
files and just copy&pasting the previous code back in.
Correction utilities
There are also automated tools to examine and rewrite text files
(sed
/awk
orrecode
).
For PHP specifically there's thephptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
Whitespace after
?>
If the error source is mentioned as behind the
closing?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing
?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonlyinclude()d
scripts are the culprit.)
Error source mentioned as "Unknown on line 0"
It's typically a PHP extension or php.ini setting if no error source
is concretized.
- It's occasionally the
gzip
stream encoding setting
or theob_gzhandler
. - But it could also be any doubly loaded
extension=
module
generating an implicit PHP startup/warning message.
- It's occasionally the
Preceding error messages
If another PHP statement or expression causes a warning message or
notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or@()
-
when either doesn't obstruct debugging later on.
No error message
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like
this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
Output buffering as workaround
PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.
The
output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to
ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if
<?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitatingob_clean()
as furher workaround.)The buffer is limited in size, and can easily overrun when left to defaults.
And that's not a rare occurence either, difficult to track down
when it happens.
Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.
See also the basic usage example
in the manual, and for more pros and cons:
- What is output buffering?
- Why use output buffering in PHP?
- Is using output buffering considered a bad practice?
- Use case for output buffering as the correct solution to "headers already sent"
But it worked on the other server!?
If you didn't get the headers warning before, then the output buffering
php.ini setting
has changed. It's likely unconfigured on the current/new server.
Checking with headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
HTML
<meta>
tag
If your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the
<head>
section.
Most browsers still accept it.
JavaScript redirect
As alternative a JavaScript redirect
can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the
<meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)
Why setcookie()
and session_start()
are also affected
Both setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)
Further links
- Google provides a lengthy list of similar discussions.
- And of course many specific cases have been covered on Stack Overflow as well.
- The Wordpress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
- Adobe Community: PHP development: why redirects don't work (headers already sent)
- Nucleus FAQ: What does "page headers already sent" mean?
- One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link).
It covers HTTP in detail and gives a few guidelines for rewriting scripts.
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
Removing the closing?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
|
show 9 more comments
No output before sending headers!
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
- Whitespace before
Intentional:
print
,echo
and other functions producing output- Raw
<html>
sections prior<?php
code.
Why does it happen?
To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
How can you find out where the premature output occured?
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Print, echo
Intentional output from
print
andecho
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensureheader()
calls occur before messages
are written out.
Functions that produce output include
print
,echo
,printf
,vprintf
trigger_error
,ob_flush
,ob_end_flush
,var_dump
,print_r
readfile
,passthru
,flush
,imagepng
,imagejpeg
among others and user-defined functions.
Raw HTML areas
Unparsed HTML sections in a
.php
file are direct output as well.
Script conditions that will trigger aheader()
call must be noted
before any raw<html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
- Place form processing code atop scripts.
- Use temporary string variables to defer messages.
- The actual output logic and intermixed HTML output should follow last.
Whitespace before
<?php
for "script.php line 1" warnings
If the warning refers to output in line
1
, then it's mostly
leading whitespace, text or HTML before the opening<?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't
compensate multiple newlines or tabs or spaces shifted into such gaps.
UTF-8 BOM
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequenceEF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its
presence. They don't visualize it (obliged by the Unicode standard).
Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systemshexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
or similar such nomenclature. Often newcomers otherwise resort to creating new
files and just copy&pasting the previous code back in.
Correction utilities
There are also automated tools to examine and rewrite text files
(sed
/awk
orrecode
).
For PHP specifically there's thephptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
Whitespace after
?>
If the error source is mentioned as behind the
closing?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing
?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonlyinclude()d
scripts are the culprit.)
Error source mentioned as "Unknown on line 0"
It's typically a PHP extension or php.ini setting if no error source
is concretized.
- It's occasionally the
gzip
stream encoding setting
or theob_gzhandler
. - But it could also be any doubly loaded
extension=
module
generating an implicit PHP startup/warning message.
- It's occasionally the
Preceding error messages
If another PHP statement or expression causes a warning message or
notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or@()
-
when either doesn't obstruct debugging later on.
No error message
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like
this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
Output buffering as workaround
PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.
The
output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to
ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if
<?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitatingob_clean()
as furher workaround.)The buffer is limited in size, and can easily overrun when left to defaults.
And that's not a rare occurence either, difficult to track down
when it happens.
Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.
See also the basic usage example
in the manual, and for more pros and cons:
- What is output buffering?
- Why use output buffering in PHP?
- Is using output buffering considered a bad practice?
- Use case for output buffering as the correct solution to "headers already sent"
But it worked on the other server!?
If you didn't get the headers warning before, then the output buffering
php.ini setting
has changed. It's likely unconfigured on the current/new server.
Checking with headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
HTML
<meta>
tag
If your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the
<head>
section.
Most browsers still accept it.
JavaScript redirect
As alternative a JavaScript redirect
can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the
<meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)
Why setcookie()
and session_start()
are also affected
Both setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)
Further links
- Google provides a lengthy list of similar discussions.
- And of course many specific cases have been covered on Stack Overflow as well.
- The Wordpress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
- Adobe Community: PHP development: why redirects don't work (headers already sent)
- Nucleus FAQ: What does "page headers already sent" mean?
- One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link).
It covers HTTP in detail and gives a few guidelines for rewriting scripts.
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
Removing the closing?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
|
show 9 more comments
No output before sending headers!
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
- Whitespace before
Intentional:
print
,echo
and other functions producing output- Raw
<html>
sections prior<?php
code.
Why does it happen?
To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
How can you find out where the premature output occured?
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Print, echo
Intentional output from
print
andecho
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensureheader()
calls occur before messages
are written out.
Functions that produce output include
print
,echo
,printf
,vprintf
trigger_error
,ob_flush
,ob_end_flush
,var_dump
,print_r
readfile
,passthru
,flush
,imagepng
,imagejpeg
among others and user-defined functions.
Raw HTML areas
Unparsed HTML sections in a
.php
file are direct output as well.
Script conditions that will trigger aheader()
call must be noted
before any raw<html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
- Place form processing code atop scripts.
- Use temporary string variables to defer messages.
- The actual output logic and intermixed HTML output should follow last.
Whitespace before
<?php
for "script.php line 1" warnings
If the warning refers to output in line
1
, then it's mostly
leading whitespace, text or HTML before the opening<?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't
compensate multiple newlines or tabs or spaces shifted into such gaps.
UTF-8 BOM
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequenceEF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its
presence. They don't visualize it (obliged by the Unicode standard).
Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systemshexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
or similar such nomenclature. Often newcomers otherwise resort to creating new
files and just copy&pasting the previous code back in.
Correction utilities
There are also automated tools to examine and rewrite text files
(sed
/awk
orrecode
).
For PHP specifically there's thephptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
Whitespace after
?>
If the error source is mentioned as behind the
closing?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing
?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonlyinclude()d
scripts are the culprit.)
Error source mentioned as "Unknown on line 0"
It's typically a PHP extension or php.ini setting if no error source
is concretized.
- It's occasionally the
gzip
stream encoding setting
or theob_gzhandler
. - But it could also be any doubly loaded
extension=
module
generating an implicit PHP startup/warning message.
- It's occasionally the
Preceding error messages
If another PHP statement or expression causes a warning message or
notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or@()
-
when either doesn't obstruct debugging later on.
No error message
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like
this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
Output buffering as workaround
PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.
The
output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to
ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if
<?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitatingob_clean()
as furher workaround.)The buffer is limited in size, and can easily overrun when left to defaults.
And that's not a rare occurence either, difficult to track down
when it happens.
Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.
See also the basic usage example
in the manual, and for more pros and cons:
- What is output buffering?
- Why use output buffering in PHP?
- Is using output buffering considered a bad practice?
- Use case for output buffering as the correct solution to "headers already sent"
But it worked on the other server!?
If you didn't get the headers warning before, then the output buffering
php.ini setting
has changed. It's likely unconfigured on the current/new server.
Checking with headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
HTML
<meta>
tag
If your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the
<head>
section.
Most browsers still accept it.
JavaScript redirect
As alternative a JavaScript redirect
can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the
<meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)
Why setcookie()
and session_start()
are also affected
Both setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)
Further links
- Google provides a lengthy list of similar discussions.
- And of course many specific cases have been covered on Stack Overflow as well.
- The Wordpress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
- Adobe Community: PHP development: why redirects don't work (headers already sent)
- Nucleus FAQ: What does "page headers already sent" mean?
- One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link).
It covers HTTP in detail and gives a few guidelines for rewriting scripts.
No output before sending headers!
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
- Whitespace before
Intentional:
print
,echo
and other functions producing output- Raw
<html>
sections prior<?php
code.
Why does it happen?
To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
How can you find out where the premature output occured?
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Print, echo
Intentional output from
print
andecho
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensureheader()
calls occur before messages
are written out.
Functions that produce output include
print
,echo
,printf
,vprintf
trigger_error
,ob_flush
,ob_end_flush
,var_dump
,print_r
readfile
,passthru
,flush
,imagepng
,imagejpeg
among others and user-defined functions.
Raw HTML areas
Unparsed HTML sections in a
.php
file are direct output as well.
Script conditions that will trigger aheader()
call must be noted
before any raw<html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
- Place form processing code atop scripts.
- Use temporary string variables to defer messages.
- The actual output logic and intermixed HTML output should follow last.
Whitespace before
<?php
for "script.php line 1" warnings
If the warning refers to output in line
1
, then it's mostly
leading whitespace, text or HTML before the opening<?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't
compensate multiple newlines or tabs or spaces shifted into such gaps.
UTF-8 BOM
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequenceEF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its
presence. They don't visualize it (obliged by the Unicode standard).
Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systemshexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
or similar such nomenclature. Often newcomers otherwise resort to creating new
files and just copy&pasting the previous code back in.
Correction utilities
There are also automated tools to examine and rewrite text files
(sed
/awk
orrecode
).
For PHP specifically there's thephptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
Whitespace after
?>
If the error source is mentioned as behind the
closing?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing
?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonlyinclude()d
scripts are the culprit.)
Error source mentioned as "Unknown on line 0"
It's typically a PHP extension or php.ini setting if no error source
is concretized.
- It's occasionally the
gzip
stream encoding setting
or theob_gzhandler
. - But it could also be any doubly loaded
extension=
module
generating an implicit PHP startup/warning message.
- It's occasionally the
Preceding error messages
If another PHP statement or expression causes a warning message or
notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or@()
-
when either doesn't obstruct debugging later on.
No error message
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like
this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
Output buffering as workaround
PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.
The
output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to
ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if
<?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitatingob_clean()
as furher workaround.)The buffer is limited in size, and can easily overrun when left to defaults.
And that's not a rare occurence either, difficult to track down
when it happens.
Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.
See also the basic usage example
in the manual, and for more pros and cons:
- What is output buffering?
- Why use output buffering in PHP?
- Is using output buffering considered a bad practice?
- Use case for output buffering as the correct solution to "headers already sent"
But it worked on the other server!?
If you didn't get the headers warning before, then the output buffering
php.ini setting
has changed. It's likely unconfigured on the current/new server.
Checking with headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
HTML
<meta>
tag
If your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the
<head>
section.
Most browsers still accept it.
JavaScript redirect
As alternative a JavaScript redirect
can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the
<meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)
Why setcookie()
and session_start()
are also affected
Both setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)
Further links
- Google provides a lengthy list of similar discussions.
- And of course many specific cases have been covered on Stack Overflow as well.
- The Wordpress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
- Adobe Community: PHP development: why redirects don't work (headers already sent)
- Nucleus FAQ: What does "page headers already sent" mean?
- One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link).
It covers HTTP in detail and gives a few guidelines for rewriting scripts.
edited May 23 '17 at 12:34
Community♦
11
11
answered Nov 6 '11 at 17:45
mariomario
126k17184256
126k17184256
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
Removing the closing?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
|
show 9 more comments
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
Removing the closing?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.
– Teson
Dec 3 '15 at 9:17
4
4
Removing the closing
?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.– Nikita 웃
Feb 8 '16 at 19:34
Removing the closing
?>
from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.– Nikita 웃
Feb 8 '16 at 19:34
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?
– Purushotam rawat
Apr 30 '17 at 19:36
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
@Purushotamrawat Did you read the part about "But it worked on the other server!?"
– mario
Apr 30 '17 at 19:52
1
1
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
@PeterSMcIntyre The UTF8 BOM presumably (fix that) / no output buffering enabled (don't rely on that).
– mario
Aug 1 '17 at 22:05
|
show 9 more comments
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes3F 3C
. You can safely remove the BOMEF 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 you can modify thedisplay_errors
or error_reporting configurations, you should rather fix the problem.
Common reasons are accesses to undefined elements of an array (such as$_POST['input']
without usingempty
orisset
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. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
add a comment |
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes3F 3C
. You can safely remove the BOMEF 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 you can modify thedisplay_errors
or error_reporting configurations, you should rather fix the problem.
Common reasons are accesses to undefined elements of an array (such as$_POST['input']
without usingempty
orisset
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. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
add a comment |
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes3F 3C
. You can safely remove the BOMEF 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 you can modify thedisplay_errors
or error_reporting configurations, you should rather fix the problem.
Common reasons are accesses to undefined elements of an array (such as$_POST['input']
without usingempty
orisset
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. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes3F 3C
. You can safely remove the BOMEF 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 you can modify thedisplay_errors
or error_reporting configurations, you should rather fix the problem.
Common reasons are accesses to undefined elements of an array (such as$_POST['input']
without usingempty
orisset
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. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
edited Jan 13 '12 at 8:22
NikiC
83.4k27168213
83.4k27168213
answered Nov 6 '11 at 17:44
phihagphihag
201k48367411
201k48367411
add a comment |
add a comment |
I got this error many times before.and I am sure all PHP programmer at-least once got this error.
To solve this error you can solve use solution as per your problem level:
Possible Solution 1:
You may have left blank spaces before or after (at the end of file after ?> ) i.e.
THERE SHOULD BE NO BLANK SPACES HERE
<?php
echo "your code here";
?>
DO CHECK FOR BLANK SPACES HERE AS WELL; THIS LINE (blank line) SHOULD NOT EXIST.
Most of the time this should solve your problem.Do check all files associated with file you require
.
Note: Sometimes EDITOR(IDE) like gedit(a default linux editor) add one blank line on save save file.This should not happen. If you are using linux. you can use VI editor to remove space/lines after ?> at the end of the page.
If this is not your case then,then you can use ob_start for output buffering like below:
Possible Solution 2:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
17
ob_start()
just hides the problem; don't use it to solve this particular problem.
– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use ofob_start()
, then what should I do for solving this problem:Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
ob_start()
doesn't "hide" the problem, it solves the problem.
– TMS
Oct 22 '15 at 20:51
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
|
show 2 more comments
I got this error many times before.and I am sure all PHP programmer at-least once got this error.
To solve this error you can solve use solution as per your problem level:
Possible Solution 1:
You may have left blank spaces before or after (at the end of file after ?> ) i.e.
THERE SHOULD BE NO BLANK SPACES HERE
<?php
echo "your code here";
?>
DO CHECK FOR BLANK SPACES HERE AS WELL; THIS LINE (blank line) SHOULD NOT EXIST.
Most of the time this should solve your problem.Do check all files associated with file you require
.
Note: Sometimes EDITOR(IDE) like gedit(a default linux editor) add one blank line on save save file.This should not happen. If you are using linux. you can use VI editor to remove space/lines after ?> at the end of the page.
If this is not your case then,then you can use ob_start for output buffering like below:
Possible Solution 2:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
17
ob_start()
just hides the problem; don't use it to solve this particular problem.
– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use ofob_start()
, then what should I do for solving this problem:Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
ob_start()
doesn't "hide" the problem, it solves the problem.
– TMS
Oct 22 '15 at 20:51
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
|
show 2 more comments
I got this error many times before.and I am sure all PHP programmer at-least once got this error.
To solve this error you can solve use solution as per your problem level:
Possible Solution 1:
You may have left blank spaces before or after (at the end of file after ?> ) i.e.
THERE SHOULD BE NO BLANK SPACES HERE
<?php
echo "your code here";
?>
DO CHECK FOR BLANK SPACES HERE AS WELL; THIS LINE (blank line) SHOULD NOT EXIST.
Most of the time this should solve your problem.Do check all files associated with file you require
.
Note: Sometimes EDITOR(IDE) like gedit(a default linux editor) add one blank line on save save file.This should not happen. If you are using linux. you can use VI editor to remove space/lines after ?> at the end of the page.
If this is not your case then,then you can use ob_start for output buffering like below:
Possible Solution 2:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
I got this error many times before.and I am sure all PHP programmer at-least once got this error.
To solve this error you can solve use solution as per your problem level:
Possible Solution 1:
You may have left blank spaces before or after (at the end of file after ?> ) i.e.
THERE SHOULD BE NO BLANK SPACES HERE
<?php
echo "your code here";
?>
DO CHECK FOR BLANK SPACES HERE AS WELL; THIS LINE (blank line) SHOULD NOT EXIST.
Most of the time this should solve your problem.Do check all files associated with file you require
.
Note: Sometimes EDITOR(IDE) like gedit(a default linux editor) add one blank line on save save file.This should not happen. If you are using linux. you can use VI editor to remove space/lines after ?> at the end of the page.
If this is not your case then,then you can use ob_start for output buffering like below:
Possible Solution 2:
<?php
ob_start();
// code
ob_end_flush();
?>
This will turn output buffering on and your headers will be created after the page is buffered.
edited Aug 22 '18 at 10:06
T.Todua
31.7k12135138
31.7k12135138
answered Aug 1 '12 at 6:43
Manish ShrivastavaManish Shrivastava
18.8k128195
18.8k128195
17
ob_start()
just hides the problem; don't use it to solve this particular problem.
– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use ofob_start()
, then what should I do for solving this problem:Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
ob_start()
doesn't "hide" the problem, it solves the problem.
– TMS
Oct 22 '15 at 20:51
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
|
show 2 more comments
17
ob_start()
just hides the problem; don't use it to solve this particular problem.
– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use ofob_start()
, then what should I do for solving this problem:Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
ob_start()
doesn't "hide" the problem, it solves the problem.
– TMS
Oct 22 '15 at 20:51
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
17
17
ob_start()
just hides the problem; don't use it to solve this particular problem.– Ja͢ck
May 15 '13 at 10:21
ob_start()
just hides the problem; don't use it to solve this particular problem.– Ja͢ck
May 15 '13 at 10:21
@Ja͢ck If I don't use of
ob_start()
, then what should I do for solving this problem: Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Ja͢ck If I don't use of
ob_start()
, then what should I do for solving this problem: Headers already sent
– Shafizadeh
Jul 14 '15 at 17:08
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
@Sajad if you're getting the error specifically because of the editor you're using, you should fiddle with the settings to make it stop causing the problem, or switch editors. If you're getting the error for any other reason, you should read through the replies in this question (specifically the accepted answer) to figure out what the problem actually is, and the solve it.
– Samsquanch
Jul 14 '15 at 19:42
3
3
ob_start()
doesn't "hide" the problem, it solves the problem.– TMS
Oct 22 '15 at 20:51
ob_start()
doesn't "hide" the problem, it solves the problem.– TMS
Oct 22 '15 at 20:51
1
1
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
I had such a problem when I upload my files to server, which supported even PHP5.3 Use server with PHP 5.6 or more
– GGSoft
Dec 9 '15 at 11:19
|
show 2 more comments
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
add a comment |
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
add a comment |
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
edited May 3 '13 at 4:34
Yogesh Suthar
26.9k175991
26.9k175991
answered Mar 24 '13 at 12:54
Ipsita RoutIpsita Rout
2,54112835
2,54112835
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
add a comment |
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
16
16
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
it's fine but if user disable java script it wont works.
– Mahendra Jella
Nov 22 '13 at 18:13
add a comment |
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
add a comment |
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
add a comment |
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
answered Nov 6 '11 at 17:45
Seth CarnegieSeth Carnegie
61k15150217
61k15150217
add a comment |
add a comment |
It is because of this line:
printf ("Hi %s,</br />", $name);
You should not print/echo anything before sending the headers.
add a comment |
It is because of this line:
printf ("Hi %s,</br />", $name);
You should not print/echo anything before sending the headers.
add a comment |
It is because of this line:
printf ("Hi %s,</br />", $name);
You should not print/echo anything before sending the headers.
It is because of this line:
printf ("Hi %s,</br />", $name);
You should not print/echo anything before sending the headers.
answered Nov 6 '11 at 17:45
SarfrazSarfraz
303k65473549
303k65473549
add a comment |
add a comment |
COMMON PROBLEMS:
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
add a comment |
COMMON PROBLEMS:
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
add a comment |
COMMON PROBLEMS:
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
COMMON PROBLEMS:
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
edited Nov 27 '18 at 22:17
community wiki
5 revs, 4 users 70%
T.Todua
add a comment |
add a comment |
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
add a comment |
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
add a comment |
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php
tag, can cause this !
Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.
I have seen these things ;)
edited May 16 '12 at 23:28
PeeHaa
50.5k43167243
50.5k43167243
answered May 16 '12 at 20:37
SliqSliq
9,0682084131
9,0682084131
add a comment |
add a comment |
Another bad practice can invoke this problem which is not stated yet.
See this code snippet:
<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>
Things are okay,right?
What if "a_important_file.php" is this:
<?php
//some php code
//another line of php code
//no line above is generating any output
?>
----------This is the end of the an_important_file-------------------
This will not work? Why?Because already a new line is generated.
Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.
From PSR-2 2.2 :
- All PHP files MUST use the
Unix LF (linefeed) line ending
. - All PHP files MUST end with a
single blank line
. - The closing ?> tag MUST be
omitted
from files containingonly php
Believe me , following thse standards can save you a hell lot of hours from your life :)
2
According to several standards (Zend for example), you shouldn't put the closing?>
tag in any file in any case any way
– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except theCR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that hasLF
(Linux end of line) instead ofCR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN
– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between?>
<?php
, removing and adding single blank line, added and omitted closing tag?>
. In Windows+ Wamp all those combinations work fine. Wierd...
– Junior M
Jun 11 '15 at 14:13
|
show 1 more comment
Another bad practice can invoke this problem which is not stated yet.
See this code snippet:
<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>
Things are okay,right?
What if "a_important_file.php" is this:
<?php
//some php code
//another line of php code
//no line above is generating any output
?>
----------This is the end of the an_important_file-------------------
This will not work? Why?Because already a new line is generated.
Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.
From PSR-2 2.2 :
- All PHP files MUST use the
Unix LF (linefeed) line ending
. - All PHP files MUST end with a
single blank line
. - The closing ?> tag MUST be
omitted
from files containingonly php
Believe me , following thse standards can save you a hell lot of hours from your life :)
2
According to several standards (Zend for example), you shouldn't put the closing?>
tag in any file in any case any way
– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except theCR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that hasLF
(Linux end of line) instead ofCR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN
– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between?>
<?php
, removing and adding single blank line, added and omitted closing tag?>
. In Windows+ Wamp all those combinations work fine. Wierd...
– Junior M
Jun 11 '15 at 14:13
|
show 1 more comment
Another bad practice can invoke this problem which is not stated yet.
See this code snippet:
<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>
Things are okay,right?
What if "a_important_file.php" is this:
<?php
//some php code
//another line of php code
//no line above is generating any output
?>
----------This is the end of the an_important_file-------------------
This will not work? Why?Because already a new line is generated.
Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.
From PSR-2 2.2 :
- All PHP files MUST use the
Unix LF (linefeed) line ending
. - All PHP files MUST end with a
single blank line
. - The closing ?> tag MUST be
omitted
from files containingonly php
Believe me , following thse standards can save you a hell lot of hours from your life :)
Another bad practice can invoke this problem which is not stated yet.
See this code snippet:
<?php
include('a_important_file.php'); //really really really bad practise
header("Location:A location");
?>
Things are okay,right?
What if "a_important_file.php" is this:
<?php
//some php code
//another line of php code
//no line above is generating any output
?>
----------This is the end of the an_important_file-------------------
This will not work? Why?Because already a new line is generated.
Now,though this is not a common scenario what if you are using a MVC framework which loads a lots of file before handover things to your controller? This is not an uncommon scenario. Be prepare for this.
From PSR-2 2.2 :
- All PHP files MUST use the
Unix LF (linefeed) line ending
. - All PHP files MUST end with a
single blank line
. - The closing ?> tag MUST be
omitted
from files containingonly php
Believe me , following thse standards can save you a hell lot of hours from your life :)
answered Nov 8 '13 at 1:29
MD. Sahib Bin MahboobMD. Sahib Bin Mahboob
14.7k21845
14.7k21845
2
According to several standards (Zend for example), you shouldn't put the closing?>
tag in any file in any case any way
– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except theCR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that hasLF
(Linux end of line) instead ofCR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN
– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between?>
<?php
, removing and adding single blank line, added and omitted closing tag?>
. In Windows+ Wamp all those combinations work fine. Wierd...
– Junior M
Jun 11 '15 at 14:13
|
show 1 more comment
2
According to several standards (Zend for example), you shouldn't put the closing?>
tag in any file in any case any way
– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except theCR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that hasLF
(Linux end of line) instead ofCR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN
– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between?>
<?php
, removing and adding single blank line, added and omitted closing tag?>
. In Windows+ Wamp all those combinations work fine. Wierd...
– Junior M
Jun 11 '15 at 14:13
2
2
According to several standards (Zend for example), you shouldn't put the closing
?>
tag in any file in any case any way– DanFromGermany
Apr 4 '14 at 11:31
According to several standards (Zend for example), you shouldn't put the closing
?>
tag in any file in any case any way– DanFromGermany
Apr 4 '14 at 11:31
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
I cannot reproduce this in Windows environment since it works using any combination (adding closing tags, blanks, pressing enter key, etc). It seems that this issue happens mostly in Linux environments.
– Junior M
Jun 10 '15 at 12:11
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
@JuniorM It should be reproducible. Can you share the code you were experimenting in a gist or something alike?
– MD. Sahib Bin Mahboob
Jun 11 '15 at 4:59
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except the
CR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that has LF
(Linux end of line) instead of CR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN– Junior M
Jun 11 '15 at 14:11
I am on Windows 7, with latest Wamp installed. I think this bug is related to hidden characters for end of line. My Wordpress' shortcodes.php was the causing the issue. I added to this file a simple function and it started to fire this "headers sent" error. I have compared my shortcodes.php with wordpress' and it was ok, except the
CR LF
(typical Windows end of line). I solve it by downloading the original file from Wordpress repo that has LF
(Linux end of line) instead of CR LF
and I also moved my function to theme's functions.php. Based on: bit.ly/1Gh6mzN– Junior M
Jun 11 '15 at 14:11
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between
?>
<?php
, removing and adding single blank line, added and omitted closing tag ?>
. In Windows+ Wamp all those combinations work fine. Wierd...– Junior M
Jun 11 '15 at 14:13
@Sahib, notice that still I cannot reproduce what is stated in this answer. The answer is totally fine for Linux environment. I have tested things such a blank between
?>
<?php
, removing and adding single blank line, added and omitted closing tag ?>
. In Windows+ Wamp all those combinations work fine. Wierd...– Junior M
Jun 11 '15 at 14:13
|
show 1 more comment
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
add a comment |
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
add a comment |
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
edited Jan 3 '17 at 11:12
community wiki
2 revs, 2 users 91%
Lupin
add a comment |
add a comment |
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
add a comment |
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
add a comment |
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
edited Aug 4 '15 at 14:46
community wiki
2 revs, 2 users 96%
Biswadeep Sarkar
add a comment |
add a comment |
read: stackoverflow.com/questions/1912029/…
– Book Of Zeus
Nov 6 '11 at 17:44
Make sure no text is outputted (
ob_start
andob_end_clean()
may prove useful here). You could then set a cookie or session equal toob_get_contents()
and then useob_end_clean()
to clear the buffer.– Jack Tuck
Apr 3 '14 at 20:16
Use the
safeRedirect
function in my PHP Library: github.com/heinkasner/PHP-Library/blob/master/extra.php– heinkasner
Jul 24 '14 at 13:29
5
~~~~~~~~~~ Your file ENCODING should not be
UTF-8
, butUTF-8 (Without BOM)
~~~~~~~~~~~– T.Todua
Sep 19 '14 at 8:00