Fitzrovian Tuesdays

"Then it is dark; a night where kings in golden suits ride elephants over the mountains." - John Cheever

Tuesday, August 28, 2012

PHP: fcgid and flush()

(Hi guys, long time no speak. This post is really just so I have a note of this myself and hopefully useful for anyone else googling the same issue...)

We had an issue with some PHP scripts timing out so tried to get the script to return some empty text just to keep the connection alive. What a pain! Finally I figured out the three things that were required:

1.
FcgidOutputBufferSize 0
in your fcgid config file (/etc/apache2/conf.d/fcgid.conf in my case, on Ubuntu 10.04)

2.
output_buffering = Off
in your PHP config file (/etc/php5/cgi/php.ini in my case, on Ubuntu 10.04)

3. And this was the real pain, because I spent ages testing with a file that was never going to work!!

You need to send at least 1024 bytes (1K) before you can flush(). This is the code for my *working* test file:

echo str_repeat(" ", 1024);
echo "Test1";

flush();

sleep(3);

echo str_repeat(" ", 1024);
echo "Test2";

(blogger doesn't like me putting the opening and closing php tags around that code, but they should be there)

If it's working correctly, you should see the first line, then three seconds later the second line. If it's not working correctly, it will wait for three seconds and load both lines at the same time.

Hope this helps someone!