- URL: https://www.laruence.com/en/2011/04/13/1991.html
- Please include attribution when republishing.
When PHP runs in FastCGI mode, PHP FPM provides a method called fastcgi_finish_request. According to the documentation, this method can improve request processing speed — if some processing can be deferred until after the page has been generated, you can use it.
It may sound a bit vague, so let me illustrate with a few examples:
<?php
echo 'example: ';
fastcgi_finish_request(); /* response complete, close connection */
/* write log */
file_put_contents('log.txt', 'To be or not to be, that is the question.');
?>
Visiting this script in a browser, you'll find the corresponding string is not printed, but the file is created. This shows that after calling fastcgi_finish_request, the response to the client has already ended, while the server-side script keeps running!
Making good use of this trait can greatly improve the user experience. While we're at it, here's another example:
<?php
echo 'example: ';
file_put_contents('log.txt', date('Y-m-d H:i:s') . " upload video\n", FILE_APPEND);
fastcgi_finish_request();
sleep(1);
file_put_contents('log.txt', date('Y-m-d H:i:s') . " transcode\n", FILE_APPEND);
sleep(1);
file_put_contents('log.txt', date('Y-m-d H:i:s') . " extract image\n", FILE_APPEND);
?>
The sleep() calls simulate some time-consuming operations; browsing isn't blocked, yet everything runs — check the log.
One last thing: Yahoo mentions "Flush the Buffer Early" in Best Practices for Speeding Up Your Web Site, i.e. using PHP's flush to send content to the client as soon as possible. It's a bit similar to fastcgi_finish_request covered here.
Reprint note: I looked into this method. When called, it sends the response and closes the connection, but it does not end PHP execution. Compared with calling flush, or the accelerating your Echo technique I introduced earlier, this one is a bit cleaner.
Also, from a portability standpoint, you can include the following in your code:
if (!function_exists("fastcgi_finish_request")) {
function fastcgi_finish_request() {
}
}
This avoids problems when the code is deployed in a non-FPM environment.
Be First to Comment