How to continue script execution in background in PHP?

php background-processing nginx fpm

There are cases where we want to continue PHP script execution in background. In other words, to fire a request and continue execution even if visitor closes browser. This might be particularly useful for collecting statistics, or store some information. Or to execute long running job from browser. To make it invisible, the request can be called via AJAX. However by default PHP will finish execution when connection is lost. To prevent this there is a built-in function ignore_user_abort or php.ini directive. The ini option can be set anywhere, including ini_set call. However calling function is more convenient. Also the HTTP connection should be closed or browser will wait for script execution finish.

When using PHP as FPM, for example with NGINX, the fastcgi_finish_request function need to be called too. When using output buffering, buffers need to be cleaned or sent to browser.

Using Ignore User Abort

In this example we do not send any data to browser. If You want to send something, the Content-Length need to be set to length of output.

// Close session - optional - only when using sessions
session_write_close();

// Instruct PHP to continue execution
ignore_user_abort(true);
fastcgi_finish_request();

// Send HTTP headers
header('Content-Length: 0');
header('Connection: close');

// Clean up buffers
if(ob_get_level() > 0)
{
        ob_end_clean();
        ob_flush();
}
flush();

// Background processing code