In PHP, how to flush content and close connection, then do extra PHP work?

I’m trying to do the following in PHP…


<?php ob_start(); echo "We'll email you as soon as this is done."; // get the size of the output $size = ob_get_length(); // send headers to tell the browser to close the connection header("Content-Length: ".$size); header('Connection: close'); // Flush the buffer ob_end_flush(); flush(); // do some logging work etc. sleep(5); exit; ?>


…but it doesn’t work. The “Connection: close” header is removed. There is a “Content-Length” header, but perhaps this is being ignored and replaced by Apache anyway.

Has anyone else been able to solve this?

My PHP mode is 5.3 FastCGI. Extra web security is enabled.[hr]
Sorry, just to clarify: I expect the page to appear quickly. Instead, it waits the full 5 seconds for sleep(5) to complete, before the page starts rendering.

I want to be able to let the client render the page, and keep the PHP going to do some logging etc.

header(“Connection: close”) doesn’t make the connection close immediately. All it does is instruct the browser to not hold the connection open (for HTTP keep-alive) after finishing the current request.

I’m not aware of any way to accomplish exactly what you’re after here. If you want to do work in the background, though, it’s probably best to start up a separate script in the background (e.g, “php myscript.php &”).

there’s an example here that seems to do what you want:

Unfortunately, that doesn’t actually work — shutdown functions run after the rest of the script has finished, but before the request is “complete”.

sorry, i was referring to this example:
not the actual function. i haven’t tried it though. it just looked promising and similar to OP’s code

Right — the code in that comment doesn’t actually work as documented. Per the documentation: