How to get Content-Length at the end of request? - php

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();
}
});

Related

PHP output buffer flush and then clean

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

How to flush data to browser but continue executing

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.

zend framework disable output for capture

I need to run post connection close processing (sending emails, refreshing caches etc) which take a long time. So in order to do this I have an action helper which will eventually down the line will check if anything needs to be done and process it.
Here's a simplified version of the output bit:
$this->getFrontController()->returnResponse(false);
$response = $this->getResponse();
$body = $response->getBody();
$response->setHeader('Connection', 'close');
ob_start();
echo $body;
$size = ob_get_length();
$response->setHeader('Content-length', $size);
ob_end_flush();
flush();
$this->run();
(Note, when live I intend on using fastcgi_finish_request but this also needs to work locally. $this->run() runs the post processing functions, no output here).
I keep getting the ol' hated Headers Sent error with this, but the exception returns no file or line number where it happened (I am guessing this is because of the nature of action helpers in Zend).
Some digging has got the error down to the setHeader() call. But I thought with returnResponse(false) they wouldn't auto send?
Is my logic to output this correct?
Edit:
Another issue is that getReponse doesn't return anything because the layout render hasn't been called, but calling Zend_Layout::getMvcInstance()->render(); gives me the layout with no content rendered to $layout->content ?
I guess ob_end_flush() sends $body, etc. but $this->run() tries to send the headers afterwards. Try to use something like $content = ob_get_contents(); and ob_end_clean() to save the buffer content to a variable and to clear the buffer without sending. Then, you can echo $content after sending your headers.

Fire-and-forget in PHP

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

Can a PHP script trick the browser into thinking the HTTP request is over?

I first configure my script to run even after the HTTP request is over
ignore_user_abort(true);
then flush out some text.
echo "Thats all folks!";
flush();
Now how can I trick the browser into thinking the HTTP request is over? so I can continue doing my own work without the browser showing "page loading".
header(??) // something like this?
Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.
<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush(); // Will not work
flush(); // Unless both are called !
// At this point, the browser has closed connection to the web server
// Do processing here
echo('Text user will never see');
?>
Headers won't work (they're headers, so they come first)
I don't know of any way to close the http connection without terminating the script, though I suppose there's some obscure way of doing it.
Telling us what you want to do after the request is done would help us give better suggestions.
But generally, I'd be thinking about one of the following:
1) Execute some simple command-line script (using exec()) that looks like:
#!/bin/sh
php myscript.php <arg1> <arg2> .. <argN> &
Then kick that off from your http-bound script like:
<?PHP
exec('/path/to/my/script.sh');
?>
Or:
2) Write another program (possibly a continuously-running daemon, or just some script that is cronned ever so often), and figure out how your in-request code can pass it instructions. You could have a database table that queues work, or try to make it work with a flat file of some sort. You could also have your web-based script call some command-line command that causes your out-of-request script to queue some work.
At the end of the day, you don't want your script to keep executing after the http request. Assuming you're using mod_php, that means you'll be tying up an apache process until the script terminates.
Maybe this particular comment on php.net manual page will help: http://www.php.net/manual/en/features.connection-handling.php#71172
Theoretically, if HTTP 1.1 keep-alive is enabled and the client receives the amount of characters it expects from the server, it should treat it as the end of the response and go ahead and render the page (while keeping the connection still open.) Try sending these headers (if you can't enable them another way):
Connection: keep-alive
Content-Length: n
Where n is the amount of characters that you've sent in the response body (output buffering can help you count that.) I'm sorry that I don't have the time to test this out myself. I'm just throwing in the suggestion in case it works.
The best way to accomplish this is using output buffering. PHP sends the headers when it's good and ready, but if you wrap your output to the browser with ob_* you can control the headers every step of the way.
You can hold a rendered page in the buffer if you want and send headers till the sun comes up in china. This practice is why you may see a lot of opening <?php tags, but no closing tags nowadays. It keeps the script from sending any headers prematurely since there might some includes to consider.

Categories