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.

1
  • 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
    Commented Nov 21, 2010 at 2:18

1 Answer 1

57

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.

6
  • So it can be used instead of asynchrone queuing to do "background job" (for instance send email) ? Commented Jun 9, 2014 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
    Commented Jun 10, 2014 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). Commented Jun 10, 2014 at 12:49
  • 2
    To make your script compatible with apache, add a function_exists() first.
    – kouton
    Commented May 26, 2015 at 7: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? Commented Apr 22, 2016 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.