I’ve been trying to complete a script that sends the proper notification to a users browser to close the connection, but allows the server to keep processing a request. My code is based on what I’ve seen on:
http://www.php.net/manual/en/features.connection-handling.php#71172
and
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
ignore_user_abort(); // optional
header('Content-Encoding: none');
header("Content-Length: $size");
header("Connection: close");
// flush all output
ob_end_flush();
ob_flush();
flush();
sleep(5);
//just a test to see if the script continues to run
file_put_contents("trash/".date('dmY-H_i_s_1').".txt", "Some text.");
file_put_contents("trash/".date('dmY-H_i_s_2').".txt", "Some text.");
file_put_contents("trash/".date('dmY-H_i_s_3').".txt", "Some text.");
When I go to run the script, sometimes it will create the first file but not write the text to it. Sometimes it doesn’t create any files. If I run the script with the return early code commented out, all three files are created just fine. Zlib compression is turned off. Any ideas?
The right way to do this is to use php in fastcgi mode and then you can use the function
fastcgi_finish_request();
it will do exactly what you need – it will close the connection to the browser but the rest of the script will continue to run to the end.
http://php-fpm.org/wiki/Features
It’s much better than relying on output buffering.