#header('Location: ' . $uri);
But it only seldom happens,what's the problem?
Don't use # to supress the error and check your logs, it is one of a few things:
Previous error output stopping the redirect?
$uri is bad sometimes
Something else in your code is bad.
Debugging is the answer.
Perhaps your script is sending some output before it for some reason. Remove the #.
Well, it is most likely because the headers were already sent due to whitespace. You'll never know this because you have a # sign in front of it that stops errors from being displayed.
Generally this whitespace might be caused by another error, or it might only happen when you include a certain file.
The other possibility is that $url is not properly formatted, or somehow the header just looks wrong to the browser. In which case the browser might choose to ignore it. Echo out the complete Header you are sending and make sure it looks right.
Finally, some browsers will stop redirecting if you have redirected too many times in a row.
The header might not be sent right away. Always use die() after header().
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
Following is the code I come to notice from a PHP file:
<?php
# Should log to the same directory as this file
$log = KLogger::instance(dirname(__FILE__), KLogger::DEBUG);
$args1 = array('a' => array('b' => 'c'), 'd');
$args2 = NULL;
$log->logInfo('Info Test');
$log->logNotice('Notice Test');
$log->logWarn('Warn Test');
$log->logError('Error Test');
$log->logFatal('Fatal Test');
$log->logAlert('Alert Test');
$log->logCrit('Crit test');
$log->logEmerg('Emerg Test');
$log->logInfo('Testing passing an array or object', $args1);
$log->logWarn('Testing passing a NULL value', $args2);
You can notice that the closing PHP tag(?>) is not present there but still all the statements within code are working perfect. I'm not getting how this could be possible to execute the code without completion of PHP tag(?>). I researched but didn't get any satisfatory explanation. Can anyone guide me in this regard? Thanks in advance.
The closing tag exists to tell the interpretter that it should stop executing the text and just output it verbatim. Unlike XML, which requires openning and closing tags to match to be valid, the PHP interpretter simply uses the tags to delimit where execution should start and stop.
Just like a PHP file could have no opening tag - meaining that the entire contents would be output, no closing tag is necessary as once the end-of-file is reached execution ends.
While I can't remember any other reason, sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:
While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.
By sending headers inadvertently, you might have introduced a security vulnerability: say, you are doing a redirection, but hence the headers are already sent, the redirection does not work and the rest of the page might be output, thus the visitor may see what she was not supposed to see. While this can be mitigated by using exit, you know the story, only if every one of us utilize good programming habits every time.
Even if letting the visitor stay in the wrong page does not have a security implication, by breaking a session behavior, or in some other ways I've encountered over years, the security and/or session cycle might have taken some sort of blow in the end.
If not security, you may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.
You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.
If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).
Bonus: a few gotchas (actually currently one) related to these 2 characters:
Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.
From the PHP Manual:
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so 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.
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 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 '?>'