This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm looking for things that might trigger the following PHP warning:
PHP Warning: Cannot modify header
information - headers already sent in
Unknown on line 0
Turned out that it was the line
ob_start("ob_gzhandler");
that caused the warning. This has been reported and fixed in 2001, it seems, but for some reason it keeps coming back.
It might be a lot of things, but as the others said, it's often just a space lying around somewhere that gets outputted and then a header() command is sent which normally is fine, but not after starting to send content back (potentially just a space in this case).
Using ob_start() stops the output from going out right away by buffering it. So it's a potential solution, or at least way to diagnose where it's coming from as zodeus said.
One common thing that causes those lose spaces are in this scenario.
global.php
<?php
$variable = 1;
$database = 'something else';
?> <-- A space here
<-- Or here
index.php
<?php
require('global.php');
$var = dosomething();
header('Location: http://www.example.com/');
?>
One way to fix that is to remove the ?> at the end of the global.php file. You don't need those, they are only useful if you start putting HTML for example after your PHP code. So you'd have:
<?php
$variable = 1;
$database = 'something else';
And when you do the require(), the space is not outputted before the header().
Just to illustrate the problems with content outputted and headers is that other common case that gives a similar error. It happens when you forget to stop the processing after a redirection using header().
if ($notLoggedIn) {
header('Location: http://www.example.com/login.php');
}
echo 'Welcome to my website'; // this will be outputted,
// you should have an exit()
// right after the header()
I think whats happening is one of the built in php functions is outputting something. I've seen this with a couple of the IMAP functions where they out put just a " " (space character) and it screws things up.
You can thry tracking it down using Xdebug or the Zend debugger, but i f you have neither
try wrapping output buffering around some of the functions you think may be cause it.
ob_start();
callYourFunction();
ob_end_clean();
Do this one function at a time and when the error goes away you'll know which function is cause you the problem, then you can either file a bug report or just leave it in as a hack. But at least then you know what function is cause the issue.
Edit: The fact that is says your output is occurring on line 0 means that it's a C level function doing the output, not any code that's been written using PHP.
Have you checked your files for unintended UTF-8 BOMs?
The error tells you that something has sent output, which would force headers to be sent, because the headers must be written before the body of the http message.
The most common problem I have found is text in headers. vis:
<?php // myfile.php
include 'header.php';
?>
and in header.php:
<?php // header.php
....
?>
What you can't see here is that there is a blank - either a space or CR/LF after the closing '?>'. This is output because the php standard says that anything outside the php tags is output as html.
The solution is to make sure that you make sure to erase everything after the closing '?>'
Related
I checked all answers in different pages and use it, but the error still appears. Please help me.
The error is:
Warning: Cannot modify header information - headers already sent by (output started at /home/iraustor/public_html/copytest/post.php:1) in /home/iraustor/public_html/copytest/post.php on line 57
The URL of form is here: http://iraust.org/copytest/contact.html
And the page that after complete the form is: http://www.iraust.org/copytest/thanks.html (or any other method to shod this message)
It has taken 2 days but answer. Please help me.
"header("Location:$Redirect_Page");"
If you issue headers, like you do for a redirect (setting Location) you MUST be sure that there's no other output before that statement, as PHP will already build the headers (however maybe not yet flushing them to the client) on the first output.
This might be the case for several reasons (unexpected error in some require, a whitespace at the beginning or end of some file, etc, but the error message you have is clear in mentioning where this output started: /home/iraustor/public_html/copytest/post.php:1.
You should double check that there's nothing before the opening and after the closing <?php ... ?> block. This applies to all included or required files in called script.
As pointed out by h7r, if you use the header function you cannot print anything before its call.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
From Header documentation on PHP.net
So, the first thing you should check is the line 57 in your post.php file: there starts the output that causes the error.
Be sure that no output is sent: also a white space or a blank lines is an output and this cause the error.
If you like, you can use the output control functions to buffer the output: in this way you can print what you want but all your outputs aren't sent immediately to browser, so you can use the header function without causing errors.
Put your code somewhere for us to look at...
Possibly PHP could be outputting an error, or a warning, etc... It might not be you for example.
no space before
I completely confused!
The form is working and the information will be send to e-mail
but the error makes feeling nervous for users
The problem solved by simple code editor (notpad++)
problem: hidden white space and non Unicode characters
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Everytime I create a website or application in PHP I must use the header() function to redirect people from page to page, but since the typical header is almost always sent before I find myself having to use output buffering functions that slow down the page. It's either that or suppress the "header already sent" errors. I just can't really find any example where an application can be built in PHP without having to violate either the two.
I am trying to know more, about how some redirect to pages without using output buffering.
edit
This is what some people assume is the possible.
<?php
$stack_errors = NULL;
if($_POST && isset($_POST['username']) && isset($_POST['password'])){
$stmt = $pdo->prepare('SELECT * FROM users where username = ? AND password = ?');
$stmt->execute(array($_POST['username'], $_POST['password']);
if($stmt->rowCount() == 0){
$stack_errors = 'error, username or password is incorrect';
}else{
$stack_errors = false;
}
}else{
$stack_errors = 'please enter username and password to log in';
}
if(false === $stack_errors){
header('Location: /success.php');
exit;
}
?>
<html>
<head></head>
<body>
<form>
<input ...>
<input ...>
<?php if($stack_errors){
echo $stack_errors;
}
<form>
A well-written application should not have a problem with output being sent "too early", and causing PHP to issue HTTP headers:
Firstly, decisions which might lead to a redirect should happen during processing of input and making business decisions; this code should be entirely complete before any content is output to the page. This ensures that your classes and functions have a single responsibility, and allows you - at least in theory - to replace the output without rewriting the whole application, e.g. to create a machine-readable API version. Contrary to your comments, the importance of this principle increases when you are working on larger projects.
Secondly, PHP itself might output errors and warnings, but these should be turned off on production systems using the display_errors ini setting. You don't want users seeing the gory details of every mistake in your code - at best, they'll judge it; at worst, they'll probe it for security holes.
Thirdly, others have pointed out issues with stray whitespace outside PHP tags, and Unicode BOMs added by editors. These can be tricky to track down, but by no means impossible - a decent editor will have functions to show whitespace, and to save without a BOM. Trailing whitespace can be avoided by not using a closing ?>, since it is implied at the end of a file. A small amount of output will also be swallowed if you use the gzip "output filter"; this doesn't buffer the whole output, but will buffer a few bytes at a time so it has something to compress, so gives you a bit of a get-out.
Headers are only sent when your PHP page produces output. If your file begins immediately with a <?php block (no whitespace, Unicode BOM, etc. before it), it won't produce any output before you get a chance to set your custom headers.
If your code is including/requiring any other PHP files before setting headers, make sure those files don't do any unwanted output either. Even if your include file is nothing but a big <?php block, check for whitespace/BOM at the beginning as well as whitespace at the end (such as a newline after the ?>).
Of course the header in the HTTP protocol is sent as first in the response. That's the reason it is called "header". You have to ensure in your code logic, that headers are sent before any other output. If you want to process and output any data before you make the decision which headers are to be sent, there is no other way than output buffering. PHP then does the job for you. You can flush and end output buffering as soon as you are sure that no further headers are to be sent.
Ok, so I am working on this login system and of course when the user logs in i regenerate the session id.
But after I regenerate my session id i also want to set a token to be stored in a cookie. However I seem to not be able to do that on the same page. I get an error that says:
Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /htdocs/somesite/test.php on line 44
Warning: Cannot modify header information - headers already sent by (output started at //htdocs/somesite/test.php:76) in /htdocs/somesite/test.php on line 54
This what I am doing right now:
session_regenerate_id();
setcookie("Foo","Bar", time()+$CookieExpireTime,"/");
I am wondering if there's a work around this. It's working when I'm testing it on localhost, but not on the server...
Common Cause:
This warning is often caused by a blank space or extra line at the beginning or end of a .php file.
Check the error for the filename that generated the error (ie: the "output started at...." filename), open that file in your text editor and remove the extra spaces or lines immediately before the first
Other Causes: Syntax errors
In the example above, you'll see output started at /....includes/something/something/something.php:12. The includes/something/something/something.php is the filename you need to be concerned about. The :12 means that the problem you need to fix is on line 12.
In that same example, the "in /includes/something_else.php on line 67" message can be completely ignored. It is not the problem. It is the one that discovered that the problem had already occurred.
If the "headers already sent" error appears AFTER any other error, then you need to fix that other error FIRST. (The error message itself is what caused headers to be sent, so fixing that error will cause the second error to go away too.)
If the "started at" refers to line 1, then it's either a space before the opening <?php tag or it's incorrect encoding on the file.
Remember, if your language is in UTF8, then you MUST encode the file as "UTF8-without-BOM", else the BOM (byte-order-mark, an invisible character at the beginning of the file) will cause this same headers-already-sent error.
Summary:
a) look for where it 'started at'
b) track the line number
c) check what's normally happening on that line.
If it's the end of the file, then it's blank spaces.
If it's the start of the file, it's likely spaces or incorrect encoding.
Elsewhere it could be a syntax error or the result of an "echo()" statement which is displaying info or perhaps debug code.
Common syntax errors include the use of single-quotes inside statements that already have single-quotes. Check to be sure your quotes aren't mismatched. If you need to use single-quotes while inside other single-quotes, change yours to \' instead of just '.
d) the rest of the info simply shows other execution information, mainly the part of the code that discovered that it cannot proceed as expected due to the problem that happened in the 'started at' location.
Source: zen-cart.com
Another similar thread on SO: How to fix "Headers already sent" error in PHP
I hope this helps.
The problem isn't with the two functions, the problem is that you cannot call session_regenerate_id() once any output has been sent to the page. That function, like header() has to be called before any sort of output is sent to the page.
Either re-structure your page so that this function is called before any output is sent, or use output buffering so that this function is called before any page content is sent.
I hope everyone's holidays are going well.
Another PHP related question here. I am using output buffers in my script, for what I have recently learned is an invalid reason (so I can pass headers later in the script). I now realize that I should be storing all output in a variable or some other sort of storage until I am ready to output at the end of the script instead of using output buffers. Unfortunately, I have already coding these functions and the spontaneous output of html into my pages already. I was hoping to be able to fix this problem in version 2 of the script, as I have strict deadlines to meet with this version.
To the question at hand. I was planning to do this, but apparently die() and exit() functions do not work so well with output buffers? I have exit() after all of my error messages, and instead of ending the execution at that point, it seems the script keeps going due to the output buffer. I have tested this hypothesis by removing the output buffers and the exit() functions work as expected.
Is there a way I change this behaviour, or should I go back to the drawing board and begin replacing my older pages? Also, can someone please explain to me why we should keep output till the end? I'm always interested in learning.
Thanks in advance everyone! Enjoy the last few days of 2010!
While I'll leave the headier and more abstract questions to more intelligent minds than I, I would recommend that you create a wrapper exit() function to simplify the code when you have errors.
i.e-
if(!$good)
{
trigger_error('bleh', E_USER_WARNING);
errorExit();
}
function errorExit()
{
ob_flush();
exit();
}
And replace all your exits with that function call and that way the buffer is flushed and the program will exit at the proper time.
Difference between header and the actual page content is basically only the position where they occur.
As the name suggests, header is in the beginning of the output. After that two carriage/returns (enter symbols) are sent and everything after that is presumed to be content.
Therefore, if you echo something and then want to change the header, it cannot be done. The content part already closed header part. What you would send as new header would now display as plain text (should PHP interpreter not stop you, which it does).
As for the other part of the question, ob_flush is a good solution as noted by Patrick.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
include('header.php');
$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];
$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query
$MyDB->run();
header('Location:index.php');
exit;
The above code keeps giving me an issue with the redirect. The error is the following:
Warning: Cannot modify header information - headers already sent by (output
started at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php:15) in
/Applications/MAMP/htdocs/testygubbins/OO/test/form.php on line 16.
I am totally flummoxed by this. Does anyone know what I should be doing to make it work?
EDIT
header.php code:
<?php
include('class.user.php');
include('class.Connection.php');
$date = date('Y-m-j');
?>
<html>
<head>
<link rel=StyleSheet href="css/style.css" type="text/css" media=screen>
<title>Test</title>
</head>
<body>
<div id="page">
Look carefully at your includes - perhaps you have a blank line after a closing ?> ?
This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.
Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.
(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).
Finally, as the PHP manual page for header points out, you should really use full URLs to redirect:
Note: HTTP/1.1 requires an absolute
URI as argument to Location:
including the scheme, hostname and
absolute path, but some clients accept
relative URIs. You can usually use
$_SERVER['HTTP_HOST'],
$_SERVER['PHP_SELF'] and dirname() to
make an absolute URI from a relative
one yourself:
COMMON PROBLEMS:
1) There should be NO output (i.e. echo... or HTML parts) before the header(...); command.
2) After header(...); you must use exit();
3) Remove any white-space(or newline) before <?php and after ?> tags.
4) Check that php file (and also other .php files, that are included) -
they should have UTF8 without BOM encoding (and not just UTF-8). Because default UTF8 adds invisible character in the start of file (called "BOM"), so you should avoid that !!!!!!!!!!!
5) Use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting. And tell the error.
7) If none of above helps, use JAVASCRIPT redirection (however, discouraged method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
Alternatively, not to think about a newline or space somewhere in the file, you can buffer the output. Basically, you call ob_start() at the very beginning of the file and ob_end_flush() at the end. You can find more details at php.net ob-start function description.
Edit:
If you use buffering, you can output HTML before and after header() function - buffering will then ignore the output and return only the redirection header.
Try This :
**ob_start();**
include('header.php');
$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];
$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query
$MyDB->run();
header('Location:index.php');
**ob_end_flush();**
exit;
Look at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php line 15.
At that position, it makes some output. Fix it. :)
If I understand correctly, something has already sent out from header.php (maybe some HTML) so the headers have been set. You may need to recheck your header.php file for any part that may output HTML or spaces before your first
EDIT: I am now sure that it is caused from header.php since you have those HTML output. You can fix this by remove the "include('header.php');" line and copy the following code to your file instead.
include('class.user.php');
include('class.Connection.php');
$date = date('Y-m-j');
You may have some "plain text" somewhere in php files that is interpreted as script output. It may be even a newline before or after the php script tag specifier (less-than + question mark + "php").
Besides, if I remember correctly, according to http specification, the "Location" header accepts only full URLs, not relative locations. Have that in mind too.
Don't include header.php. You should not output HTML when you are going to redirect.
Make a new file, eg. "pre.php". Put this in it:
<?php
include('class.user.php');
include('class.Connection.php');
?>
Then in header.php, include that, in stead of including the two other files.
In form.php, include pre.php in stead of header.php.
Your include produces output, thereby making it impossible to send a http header later. Two option:
Move the output somewhere after the include.
Use output buffering, i.e. at the very start of your script, put ob_start(), and at the end, put ob_flush(). This enables PHP to first wait for all the output to be gathered, determine in what order to render it, and outputs it.
I would recommend you learn the second option, as it makes you far more flexible.
also try include_once() instead of include() that can also work
Also see your php file text encoding. Mine was UTF-8 with BOM and it prevented the script to work. But now works flawlessly after removing the BOM...
Try redirection with JavaScript:
<script type="text/javascript">
window.location.href='index.php';
</script>