I am trying to do this:
Display "a" for 1 second, clear screen display only "b" for 1 second, clear screen display only "c".
This is what I have so far, buts it's not working:
header("Content-type: text/html; charset=utf-8");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
set_time_limit(0);
ob_implicit_flush(1);
echo "a";
ob_flush();
ob_clean();
sleep(1);
echo "b";
ob_flush();
ob_clean();
sleep(1);
echo "c";
Output buffer doesn't work that way, it's a one way street. What has been passed to the browser has been sent from the server and you don't have access anymore to that data and you don't have any control over the data that the user has already received.
The only way to do this would be to send control characters to clear the screen, but those don't fall into the characters browsers will accept.
In theory you could send \x08 (backspace), but it will not work on anything else but something that allows using these ASCII control characters. Are you working with a terminal or a graphical browser? The first one might accept, the latter most unlikely ever would.
There is no screen. There is only output that is sent from your server (PHP runs on the server) to the browser.
The ob functions use output buffering. Using this technique, you can buffer the output (result of echoes and such) on the server, and even descard or modify it, before sending it to the client (the browser).
Your understanding of those functions is wrong, as is the way you are using them.
At best, the result could be that 'a' appears first, and 'b' would appear a second later. But there are a couple of issues. First of all, you don't start output buffering at all (using ob_start). Secondly, the server might already send the 'a' to the browser, but the browser will also see that it's only one letter, and that the response is still going on, so it will likely not display it. A half response is usually just an incomplete page, so browsers will also buffer the response they get in order not to display a bunch of garbage on screen. They will in most cases only show the response when it is received completely, or when the connection was broken before that.
So in short, this is not going to work. You will need either JavaScript or a meta redirect to fix this.
In a JavaScript-enabled browser, you might do this (no PHP needed):
<body/>
<script type="text/javascript">
// Get the body
var doc = document.getElementsByTagName('body')[0];
// Set its text.
doc.innerText = 'A';
// Replace it with another text after a 1000 milliseconds.
setTimeout(function(){
doc.innerText = 'B';
}, 1000);
</script>
I wouldn't rely on PHP code to do this and hope that it is timed correctly. Use the php to build your page and retrieve any data you need, and use javascript or jquery to do that you are trying to do. With javascript/jquery, you can dynamically set the html of a page without refreshing. Take a look over here
Related
headers_sent will tell me when output was sent to the browser. However, it can be that no body was sent, e.g. 302 redirect.
How do I tell in register_shutdown_function context what content has been sent to the browser, or at least what was Content-Length.
The content lenght header will no being set by apache if it is a PHP script. This is because the webserver can't know about this as the content is dynamically created. However the headers have to sent before the body. So the only way to get the length of the content is to generate it, obtain it's length, send the header and then send the content.
In PHP you can use ob_* set of functions (output buffering) to achieve this. Like this:
ob_start();
echo 'hello world'; // all your application's code comes here
register_shutdown_function(function() {
header('Content-Length: ' . ob_get_length());
ob_end_flush();
});
Warning This will be unreliable if you are using gzip encoded transfer. There has been posted a workaround on the PHP web site,
Also you might need to know that output buffers can be nested in PHP. If there is another ob_start() call in my example above than you'll end up seeing nothing in the browser because just the inner buffer gets flushed (into the outer one)
The following example takes care on this. In order to ease the process it just overwrites the header multiple times, which shouldn't be a performance issue as header() is basically a simple string operation. PHP sends the headers only before some output or at the end of the script.
Here comes the code which has been tested gzip safe and works reliable with nested unclosed buffers:
ob_start('ob_gzhandler');
echo 'hello world';
// another ob_start call. The programmer missed to close it.
ob_start();
register_shutdown_function(function() {
// loop through buffers and flush them. After the operation the
// Content-Lenght header will contain the total of them all
while(ob_get_level()) {
header('Content-Length: ' . ob_get_length(), TRUE);
ob_end_flush();
}
});
I have a ob_start() and a corresponding ob_flush(). I would like to flush a portion of data and continue executing the rest. Using ob_flush() didn't help. Also if possible rest needs to happen without showing loading in browser.
EDIT:
I don't want to use ajax
I have done this in the past and this is how I solved it:
ob_start();
/*
* Generate your output here
*/
// Ignore connection-closing by the client/user
ignore_user_abort(true);
// Set your timelimit to a length long enough for your script to run,
// but not so long it will bog down your server in case multiple versions run
// or this script get's in an endless loop.
if (
!ini_get('safe_mode')
&& strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE
){
set_time_limit(60);
}
// Get your output and send it to the client
$content = ob_get_contents(); // Get the content of the output buffer
ob_end_clean(); // Close current output buffer
$len = strlen($content); // Get the length
header('Connection: close'); // Tell the client to close connection
header("Content-Length: $len"); // Close connection after $len characters
echo $content; // Output content
flush(); // Force php-output-cache to flush to browser.
// See caveats below.
// Optional: kill all other output buffering
while (ob_get_level() > 0) {
ob_end_clean();
}
As I said in a couple of comments before, you should watch out for gzipping your content, since that will alter the length of your content, but not change the header about it. It also can buffer your output, so it won't get send to the client instantly.
You could try letting apache know to not gzip your content by using apache_setenv('no-gzip', '1');. But this will not work if you use rewrite-rules to go to your page, since then it will also modify those environment variables. At least, it did so for me.
See more caveats about flushing your content to the user in the manual.
ob_flush writes the buffer. In other words, ob_flush tells PHP to give Apache (or nginx/lighttpd/whatever) the output and then for PHP to forget about it. Once Apache has the output, it does whatever it wants with it. (In other words, after ob_flush it's out of your control whether or not it gets immediately written to the browser).
So, short answer: There's no guaranteed way to do that.
Just a guess, you're likely looking for AJAX. Whenever people are trying to manipulate when page content loads as you're doing, AJAX is almost always the correct path.
If you want to continue a task in the background, you can use ignore_user_abort, as detailed here, however, that is often not the optimal approach. You essentially lose control over that thread, and in my opinion, a web server thread is not where heavy processing belongs.
I would try to extract it out of the web facing stuff. This could mean a cron entry or just spawning a background process from inside of PHP (a process that though started from inside of script execution will not die with the script, and the script will not wait for it to finish before dying).
If you do go that route, it will mean that you can even make some kind of status system if necessary. Then you could monitor the execution and give the user periodic updates on the progress. (Technically you could make a status system with a ignore_user_abort-ed script too, but it doesn't seem as clean to me.)
this is my function
function bg_process($fn, $arr) {
$call = function($fn, $arr){
header('Connection: close');
header('Content-length: '.ob_get_length());
ob_flush();
flush();
call_user_func_array($fn, $arr);
};
register_shutdown_function($call, $fn, $arr);
}
wrap the function to be executed in the end, after php close the connection. and of course the browser will stop buffering.
function test() {
while (true) {
echo 'this text will never seen by user';
}
}
this is how to call the function
bg_process('test');
first argument is callable,
second argument is an array to be passed to 'test' function with an indexed array
Note : I don't use ob_start() at the beginning of the script.
I have an article explaining how this can be achieved using apache/mod_php on my blog here: http://codehackit.blogspot.com/2011/07/how-to-kill-http-connection-and.html Hope this helps, cheers
If you are using PHP-FPM:
ignore_user_abort(true);
fastcgi_finish_request();
Above two functions are the key factors which ignore_user_abort prevents error and fastcgi_finish_request closes client connection.
fastcgi_finish_request
This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.
not working on Apache.(PHP 5 >= 5.3.3, PHP 7)
Use:
header("Content-Length: $len");
..where $len is the length of the data to be flushed to the client.
I don't have the background to know when and where this is going to work, but I tried on a few browsers, and all returned instantly with:
<?PHP
header("Content-length:5");
echo "this is more than 5";
sleep(5);
?>
edit: Chrome, IE, and Opera showed this, while FireFox showed this is more than 5. All of them closed the request after that though.
Final update
Seems like I did make a very simple error. Since I already have a stream implementation I can just not start reading from the stream :D
I'm trying to achieve fire-and-forget like functionality in PHP.
From php.net
<?php
ignore_user_abort(true);
header("Content-Length: 4");
header("Connection: Close");
echo "abcd";
flush();
sleep(5);
echo "Text user should not see"; // because it should have terminated
?>
This works if I open the script with a browser. (shows "abcd").
But if I open it with file_get_contents or some stream library it will wait for ~5 seconds and show the second text as well.
I'm using PHP 5.2.11 / Apache 2.0
Update
I seems there is some confusion about what I'm trying to accomplish.
I don't want to hide output using output buffers (that's stupid). I want to have the client terminate before the server starts a possibly lengthy process (sleep(5)) and I don't want the client to wait for it (this is what fire-and-forget means, sort off).
The use of output buffers is merely a side effect. I've amended the sample code without the use of output buffers.
What I don't understand is: why does this script behave differently when accessing it from the browser vs. fetching it in PHP with file_get_contents("http://dev/test.php") or some stream library? What I've seen in testing is that for instance stream_get_contents will actually block for 5 seconds before it returns any output at all, the is quite the opposite of what I want.
Update2
Some more results:
The browser somehow responds to the flush(). I can't figure out how to replicate this behavior with streams in PHP, my streams keep blocking.
I've tried fread and found that it behaves similar to stream_get_contents.
Specifying a maxlength has no effect, it will still block for ~5 seconds.
Changing the blocking mode has no effect (other than generating a bunch more calls to stream_get_contents()). It will wait ~5 seconds before returning anything.
stream_set_read_buffer has no effect (tested on a PHP 5.3.5 sever)
The second portion of text is showing up because you're stopping output buffering with ob_end_flush() and ob_end_clean(). When that happens PHP outputs content as normal. Try something like the following:
<?php
ob_start(); // turn on output buffering
print "Text the user will see.";
ob_flush(); // send above output to the user and keep output buffering on
print "Text the user will never see";
ob_end_clean(); // empty the buffer and turn off output buffering. your script should end here.
?>
It's important for ob_end_clean() to appear at the end of the script. It empties the buffer and does not send its contents to the user, thus keeping everything after ob_flush() hidden.
How do you access the script using file_get_contents? How do you access it with your browser? If you access the script without "http://", of course it will never get executed. Use the same URL as in the browser.
Edit:
The browser will render the page even before the connection is closed. Even if you flush, I don't think the connection is closed. You can fire up Wireshark and check. stream_get_contents and file_get_contents will block until they have all the output. Even if you flushed, they can't be sure that there isn't more content. Since the content-length header didn't seem to make {file,stream}_get_contents return earlier, you probably need to implement your own buffering, ala. fopen, read, fclose.
Seems like I did make a very simple error. Since I already have a stream implementation I can just not start reading from the stream :D
I stumbled upon this function which promised to work across IE, FF & Chrome. But it does not work in Chrome. Is there a work around?
function buffer_flush(){
echo str_pad('', 512);
echo '<!-- -->';
if(ob_get_length()){
#ob_flush();
#flush();
#ob_end_flush();
}
#ob_start();
}
Here's how I got flush() working in a while loop in Chrome 12.0.742.122 with PHP 5.3.6:
echo("<html><body>");
while(1) {
echo(str_pad($my_string_var,2048," "));
#ob_flush();
flush();
}
Using a lesser str_pad value worked too, but it would take a bit longer for the first output to appear. If any of the other lines were missing, nothing would appear.
The "#" isn't strictly necessary, but it prevents the log from filling up with "nothing in the buffer" notices.
And of course if you have a pre-existing page, just make sure the <html> and <body> tags are in there; I was writing a page from scratch.
With flush()/ob_flush() you only send the output to the browser, but its still up to the browser, when it displays it. I assume, that chrome just waits, until it has enough data received to display a "useful" page, instead of some fragments.
Some suggestions anyway:
Avoid using # (especially if you don't know exactly, what it does)
If you don't call ob_end_*(), you don't need to call ob_start() again. Its inefficient
function buffer_flush(){
echo '<!-- -->'; // ?
ob_flush();
flush();
}
Some browsers (IE6 at the very least, and possibly chrome) require a certain amount of "useful" characters (i.e. not spaces) before outputting anything. In the case of IE6, it even is the compressed data's size that needs to be pushed.
function force_flush() {
echo "\n\n<!-- Deal with browser-related buffering by sending some incompressible strings -->\n\n";
for ( $i = 0; $i < 5; $i++ )
echo "<!-- abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono -->\n\n";
while ( ob_get_level() )
ob_end_flush();
#ob_flush();
#flush();
} # force_flush()
There are several components that can have impact on this issue.
Read carefully through the documentation of this function:
http://www.php.net/manual/en/function.flush.php
One solution I had was using Apache2 with mod-php (not as fcgi but as native apache-module) and Chromium. The result came immediately and the script was still running and sending more results.
After typing the following two code-lines every echo-command will immediately push the text to the whatever-PHP-backend:
ob_implicit_flush(1);
#ob_end_flush(); // set an end to the php-output-buffer!
But this php backend can have its own buffer. For example I run nginx as webserver and php is used by the fast-cgi module. Nginx itself has its own buffer ... and so on.
The Browser also can buffer the request. But as I experience Chromium (or Google Chrome) has a verry small or no buffer.
Please read the documentation of every function I mentioned to understand what they really do - but specially the documentation of flush().
Personal hint: Do not put extra characters into the output-buffer but read and understand the configuration of your server.
EDIT:
If you have gzip enabled the whole response from the server will be buffered.
I found that a content type header really makes it work in chrome after few trial and errors.
But i don't know why chrome does not flush otherwise.
after searching for more answers i read that chrome flushes as you expect only when a valid content type is set. fine.
Here is the code i experimented.
<?php
header('Content-Type: text/html; charset=UTF-8');
echo 'starting...';
flush();
echo 'to sleep...';
flush();
sleep(5);
echo 'awake';
if i do not include the content type header i get like the following in one shot after 5 seconds. so what we expect did not work.
starting...to sleep...awake is displayed and the script terminates.
where as when i gave the content type like the above with the subtype(charset) then
starting...to sleep... is displayed immediately and then after 5 seconds awake is displayed.
i am just blindly assuming that with respect to the content type header chrome shows the output.
Besides when i gave 'Content-Type: text/plain' or 'Content-Type: text/html' it did not work. it worked only with the subtype 'charset=[sometexthere]'.
were as application/json worked. and i did not experiment with more mimes.
The reason i am here is
i wanted to use readystate 3 in ajax response. it works fine except chrome and safari. since chrome is using webkit it is the same in both i think.
in other browsers including IE the flushing is working as expected and also the readystate=3 but in chrome and safari i just used the above workaround.
here is the screenshot of the readystate - responsetext from the above php script
in the image there a two sets of response the first one with readystate 3 and responsetext as empty when content type is not used.
in the second response you can see ready state 3 has responsetext with the expected output. this is when content type is used.
so... Chrome only knows.
when used str_pad
When you use string padding you can get more expected result. i tried with 1024 as the above answers suggested but only with content type set.
if padding is used and no content type is set then it did not work.
and
i had raised a question similar to this and i am going to add my own answer by linking this answer to that and back to back... so that it will be easy for users to get more details. hhmmm.
This is purely for learning more about output buffering and nothing more. What I wish to do is echo a string to the browser, sleep 10 seconds, and then echo something else. Normally the browser would wait the full 10 seconds and then post the whole result, how I would I stop that? An example:
ob_start();
echo "one";
sleep(10);
echo "two";
faileN's answer is correct in theory. Without the ob_flush() the data would stay in PHP's buffer and not arrive at the browser until the buffer is implicitly flushed at the end of the request.
The reason why it still doesn't work is because the browsers also contain buffers. The data is now sent out correctly, but the browser waits after getting "one" before it actually kicks off rendering. Otherwise, with slow connections, page rendering would be really, really slow.
The workaround (to illustrate that it's working correctly) is, of course, to send a lot of data at once (maybe some huge html comment or something) or to use a tool like curl on the command line.
If you want to use this sending/sleeping cycle for some status update UI on the client, you'd have to find another way (like long-polling and AJAX)
ob_start();
echo "one";
ob_flush();
sleep(10);
ob_start();
echo "two";
Is that what you mean?
If I understand correctly, you are trying to print part of the response on screen, wait 10 seconds and output the rest, all this when the page is loading. This would require some client side scripting for that as PHP will output the entire response at the end.
I think a combination of ob_flush and flush might work, but buffering is not handled the same on every browser (such as IE).
I use the JavaScript's setTimeOut() function for this. It works fine.
Additionally, you can use the <noscript> tag for browsers where JavaScript is disabled.
$txt = setPageHeader(); // a PHP function that returns a new DOCTYPE
// plus <html><head>(...)</head>,
// plus an opening <body> tag
echo 'All things were completed. You should be redirected in about 3 seconds';
$txt .= '<script type="text/javascript">';
$txt = $txt.'function Rediriger() {document.location.replace(\'http://yoursite.com/yourpage.php?anticaching='.rand().'\');}';
$txt .= 'setTimeout (\'Rediriger()\', \'3000\')';
$txt .= '</script>';
$txt .= '<noscript>Javascript is disabled in your browser. Click here for being redirected.</noscript>';
$txt .= '</body></html>';
echo ($txt);
With ob_flush() - but that will clear the buffer contents. You can't inject a delay into a buffer, it just doesn't work like that.
You either output the entire buffer at once, or hold on to the entire buffer for later use.
Can't because browser waiting for full version of document because what browser engine parsing half of XHTML page and after this (how to render half of XML?) reading other part.
You must think about send header before to inform browser as binary data was sanded then browser get you data after recv and propably get out this data on screen immediate.
I miss understand this question because i never think about inject to string buffer 10s sleep.