26

Can someone show a simple example on how to use fastcgi_finish_request() function? I googled but only found some general mention of it, some people say they use it successfully but I could not find a single example with code.

For example, I have a PHP object. To send a response to a browser I generate HTML, then returning it via getResult(). Then echo the result.

Like this:

$obj = new controller();
echo $o->getResult();

Let's say I want to take advantage of this optimization technique to send result to browser and then finish up some potentially long process like connecting to some API, like maybe Facebook API.

How would I go about doing this? I understand that basically I can call fastcgi_finish_request(); and then continue executing php script.

I just need to see example code, I'm not smart enough to figure it out by myself.

hakre
  • 193,403
  • 52
  • 435
  • 836
Dmitri
  • 34,780
  • 9
  • 39
  • 55
  • I know it requires php running as fastcgi with php-fpm. I already have it setup this way, using php 5.3 as fastcgi and lighttpd as web server. – Dmitri Nov 21 '10 at 02:18

1 Answers1

56

I understand that basically I can call fastcgi_finish_request(); and then continue executing PHP script.

Yes, that's all you have to do.

$obj = new controller();
echo $o->getResult();
fastcgi_finish_request();
do_facebook_thing();

To convince yourself it is working, do this:

echo "Test";
fastcgi_finish_request();
sleep(10);

If you remove the second line, then you will see that the browser has to wait 10 seconds.

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Matthew
  • 47,584
  • 11
  • 86
  • 98
  • So it can be used instead of asynchrone queuing to do "background job" (for instance send email) ? – Thomas Decaux Jun 09 '14 at 17:51
  • 1
    @ThomasDecaux, it could, but you would still be holding on to a web process while that task was running. Ultimately, it's worthwhile to use a proper queue that is completely detached from the web processes for blocking operations not needed for the page to be served. – Matthew Jun 10 '14 at 12:14
  • 1
    sure I agree is the laziest solution ^^ But it's a good trick to know (I am using it for logging, if there is an error, I send the error message to the user then send an email to the programmer). – Thomas Decaux Jun 10 '14 at 12:49
  • 2
    To make your script compatible with apache, add a function_exists() first. – kouton May 26 '15 at 07:36
  • Hi. I've tried your example and it works, yeah. BUT! If i refresh the page quickly (several time per second), then i can see that last queries takes too long time (maybe from 3 to 6 seconds). What is the reason for it? nginx workers, etc? – Dmitriy Apollonin Apr 22 '16 at 09:23
  • so if apache is used with php-fpm and I call this function, the client connection is closed, php keeps running in the background but what about Apache will it keep running? – OAH Oct 11 '20 at 20:16