In PHP, is there a (ready-made) way to check if a part of the output has already been sent to the client?
I know that with headers_sent() you can check if the headers have already been sent, but I also want to check if any output has been sent (so that e.g. the HTTP header Content-Length > 0).
(Notice that ob_start() starts output buffering from the moment when it is called. But third-party systems implementing my code might already have sent output, thus output buffering is unusable as far as I know.)
You could wrap your own ob_start around everything else and flush it when you decide to. It works even if other ob_start's and flushes are inside. Take this example :
ob_start();
[...]
//some 3rd party app which is included on the way
[...]
ob_start();
[...]
ob_flush(); //at this moment the buffer isn't flushed to the client
//but to the parent ob_start, which is yours, so no output
//is sent yet
[...]
//ok, we're done, we can output now
ob_flush();
PHP in most cases sends headers to Apache only with some content or on the end of script execution. So, if headers are sent, some content is sent too. Furthemore, as I understand, Content-Length is calculated anyway after the script execution.
Related
I need to echo some output while executing php file ,beacuse execution takes 10 sec and end of 10sec page should be directed via header("Location:test.php)
However If I use ob_start and ob_implicit_flush(true) at the same time , we cannot direct page and getting
Warning: Cannot modify header information - headers already sent by
I also need to use ob_implicit_flush(true) to print output while execution.
How can I display output and direct page ?
You cannot output both body content and a redirect header in the same response, much less output the body before the header. The HTTP headers come first, so you cannot output a body before headers and you cannot output headers after the body has been output. Further, a redirect header causes the request to be immediately redirected before the browser will display any of its content, so the entire thing doesn't work on two levels.
If you want to display anything while the server is doing something, you'll need to use Javascript in some form or another.
If you use header() function there MUST be no output BEFORE it. But of course it can be after using the function.
ob_start starts the buffer to work while ob_implicit_flush tells to use no buffer at all. So the two functions cannot be combined that way.
Example:
ob_start(); //set buffer on
print('Hello World'); //no output since buffer on
ob_implicit_flush(true); //buffer switched off again
print('Test'); //prints 'Hello World' and 'Test'
header('Location: ...'); //ERROR: output already done
You have now to decide if you want to output information from your script OR make the redirection.
Output something AFTER header is possible but it makes no sense as you will not see it anymore.
Maybe you can use the ob_get_length() function to check if there was some output and then decide if you switch page or output the buffer:
ob_start(); //set buffer on
print('Hello World'); //no output since buffer on
if(ob_get_length() > 0)
ob_end_flush();
else
header('Location: ...'); //will not be executed if output was generated
<?
echo "lalala";
header("Location: http://www.google.com/");
If i put this in a plain php file and deliver over a standard apache2 server with mod-php (PHP Version 5.3.2-1ubuntu4.10) the redirect to google works.
<?
echo "lalala";
flush();
header("Location: http://www.google.com/");
this code does obviously not produce a working redirect.
My question is how the first code is beeing processed and why it works. Because I remember times when things like this were not possible. Is mod-php or apache intelligent enough to buffer the whole request and arrange headers before content?
And:
Can I rely on this if I make sure I don't flush the output manually? Because it would make my application much easier...
Output buffering is probably enabled by default. You should enable it manually if you want to rely on this functionality.
http://php.net/manual/en/function.ob-start.php
The header function ADDS an http common header to the HTTP response. So, the redirect is setted and the browser gets the 302 message before showing you the output.
flush orders php to send the http response already prepared at the point it is called. That's why the second code won't set the header (it must be setted before sending ANY output).
And, the PHP should not output a single thing until:
The script is processed (even if an error stops the parsing)
you set it to send the output somewhere in the script with flush()
Finally, check this on output control http://www.php.net/manual/en/intro.outcontrol.php
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?
If you can't send the header() before some content gets sent, use output buffering by placing an ob_start(); at the beginning of your script before anything is sent. That way, any content will be stored in a buffer and won't be sent until the end of the script or when you manually send the buffer's contents.
On another note, simply requireing another file would not generate any headers/content unless that included script sends them. The most common "hidden" cause of this is unnoticed whitespace before or after the <?php ?> tags.
As Artefacto noted, connecting to the database should not require any output. Fix whatever you're including (e.g. database_connect.php) not to output. See this search on the "headers already sent" issue, which may help you find "hidden" output.
ob_start(); // start output buffering
echo "<html......"; // You can even output some content, it will still work.
.
.
.
.
.
header("Location: mypage.php");
ob_flush(); //flush the buffer
In this case, all output is buffered. This means, the headers are processed first, then the output comes to play...
You cannot send any headers after some content has already been sent. Move the header() call to be before the require() call.
You cannot send headers after any data has been sent to the client.
However, using require does not meen that you output something. If i understand your right, you can include your database files, run your queries and then redirect the user. This is perfectly valid.
If you need to send some output (why if you need to do a redirect?) another option is to use output buffering. By using output buffering, you're not sending the data to the browser when you echo it, but you store it in a buffer. The data will be sent when you call ob_end_flush or you reach the end of the script. After ob_end_flush, you won't be able to send any new headers. You start output buffering with ob_start.
It is possible to use header() with require() when I use output buffering. That means that the whole script is buffered and first send when the script has come to an end.
I have done it by doing this
ob_start("ob_gzhandler"); //begin buffering the output
require_once('/classes/mysql.php');
// Some code where I access the database.
header('/somepage.php');
exit;
ob_flush(); //output the data in the buffer
how can I set cookies in the middle of a document, without incurring a 'headers already sent' error? What I'm trying to do is make a log out script (the log in cookie setting works...so odd. Is it because it's enclosed in an if statement?) however I've already echoed the page title and some other stuff at the top of the page, before I've made this logout happen.
Thanks!
The easiest way is to use output buffering to stop PHP from sending data to the client until you're ready
<?php
ob_start();
// your code
ob_end_flush();
?>
Output buffering stores all outputted data until the buffer is flushed, and then sends it all at once, so any echos after the start will remain buffered until the end_flush and then sent
Try to decompose your application in two parts :
First, you unset the cookie, then you redirect user on the result page. It's a common way to work.
Also try to use a framework in your development, it will improve your skills and the maintenability of your code.
Cookies are sent in the headers, which are sent before anything else is sent. Therefore, if you have actually 'echoed' something to the client (browser), your headers have also been sent.
That said, you can buffer your output and send it all once all the code has been run (ob_start() and ob_end_flush())
I don't think it's reasonable.
Why is it actually such a rule?
In the "normal case", I don't think ob_start has to be called before session_start -- nor the other way arround.
Quoting the manual page of session_start, though :
session_start() will register internal
output handler for URL rewriting when
trans-sid is enabled. If a user uses
ob_gzhandler or like with ob_start(),
the order of output handler is
important for proper output. For
example, user must register
ob_gzhandler before session start.
But this is some kind of a special case : the thing is, here, that the order of output handlers is important : if you want one handler to modify things the other did, they have to be executed in the "right" order.
Generally, if you don't use that kind of handlers (Apache and mod_deflate do a great job when it comes to compressing output, for instance), the only thing that matters is that headers must not be sent before you call session_start (because, depending on your configuration, session_start sends cookies, which are passed as HTTP headers).
And headers are sent as soon as any piece of data has to be sent -- ie, as soon as there is any output, even one whitespace outside of <?php ?> tags :
Note: If you are using cookie-based
sessions, you must call
session_start() before anything is
outputted to the browser.
ob_start indicates that PHP has to buffer data :
This function will turn output
buffering on. While output buffering
is active no output is sent from the
script (other than headers), instead
the output is stored in an internal
buffer.
This way, output is not sent before you actually say, yourself, "send the data". This means headers are not send immediatly -- which means session_start can be called later, even if there should have been output, if ob_start had not been used.
Hope this makes things a bit more clear...
If by default your output_buffering is Off and you have been unfortunate enough to send a single byte of data back to the client then your HTTP headers have already been sent. Which effectively prevents session_start() from passing the cookie header back to the client. By calling ob_start() you enable buffering and therefore delay sending http headers.
session_start might want to modify the HTTP header if certain configuration options are set. One for example is session.use_cookies that requires to set/modify the Set-Cookie header field.
Modifying the HTTP header requires that there isn’t any output that’s already sent to the client as the HTTP header is sent right before the first output is sent.
So you either ensure that there is absolutely no output before the call of session_start. Or you use the output buffering control to buffer the output so that the HTTP header can be modified even if there already is output.
session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output.
For example, the user must register ob_gzhandler before session start.
But this is some kind of a special case. The thing is, here, that the order of output handlers is important. If you want one handler to modify things the other did, they have to be executed in the "right" order.
Generally, if you don't use that kind of handlers (Apache and mod_deflate do a great job when it comes to compressing output, for instance), the only thing that matters is that headers must not be sent before you call session_start (because, depending on your configuration, session_start sends cookies, which are passed as HTTP headers).
And headers are sent as soon as any piece of data has to be sent -- ie, as soon as there is any output, even one whitespace outside of <?php ?> tags :
Note: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.
ob_start indicates that PHP has to buffer data :
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
This way, output is not sent before you actually say, yourself, "send the data". This means headers are not send immediatly -- which means session_start can be called later, even if there should have been output, if ob_start had not been used.
session_start(); should be called before any headers are sent out. ob_start() will suppress the output for a while and you can break this rule. Usually ob_start() on the top is a quick fix in case you are debugging something unknown; everything below works as expected (not just as written ;-)). I prefer to use ob_start() later to session_start().
In PHP, ob_start() is used to start output buffering. Output buffering captures all output sent to the browser and stores it in a buffer, allowing you to manipulate it before sending it to the browser.
When using sessions in PHP, it is important to call ob_start() before starting the session, as sessions rely on cookies, which are sent to the browser as part of the HTTP headers. If any output has already been sent to the browser before the session is started, the headers will have already been sent and it will not be possible to set the session cookies.
By calling ob_start() before starting the session, any output that is generated before the session is started will be captured by the buffer and will not be sent to the browser. This allows the session cookies to be set correctly, even if some output has already been generated.
In summary, ob_start() is necessary for session in PHP because it ensures that headers can be sent correctly even if there is output generated before the session is started.