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.

ob_start

Here is the code that I am using;

ignore_user_abort(true);
set_time_limit(0);
ob_start();

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");
ob_end_flush();
ob_flush();
flush();
fastcgi_finish_request();

// 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.

Caring is sharing.. thank you! -David

Twitter Button Facebook Button Google Button LinkedIn Button

Write a Comment

Comment