Process PHP Script in Background while HTML Output & ob_start(); Fix

This is how to display HTML or send a HTTP response with PHP while processing a PHP script in the background, using ‘ob_start‘ output buffering.


Here is the code that I am using;


echo '<!DOCTYPE html><body>If this works, you are taken to this page before the rest of the script finishes. Enjoy!</body></html>';

header('Connection: close');
header('Content-Length: '.ob_get_length());
header("Content-Encoding: none");

// continue with the PHP script below

The code is put together from suggestions online, you could also use ‘ob_gzhandler‘ to compress the output buffer with gzip, which I haven’t.

The “header(“Content-Encoding: none”);” is simply a paranoid measure, since this won’t work if it’s set to anything else.

When I moved from an old PHP 5 set up to using PHP 7.2 with PHP-FPM, ob_start(); stopped from working. To fix this problem, I added “fastcgi_finish_request();” to the end. Other suggestions I saw was to change the “output_buggering = 4096” line in php.ini to Off but this had no effect for me.

That’s pretty much all there is to running PHP in the background.
Thanks for reading! David.

Leave a Comment