9

I had set up a server sent event script with php and a while loop, I did not want for the script to have to keep closing and have to repoll so I put it all in a while loop.

The issue was that the script was getting stuck and I had to abandon that route and I went with a node.js websocket backend instead.

My question is, if I ever went back to making a server sent event php script, how do I implement it?
while loops do not seem to cut it as it hangs the script, and if it is just connecting and disconnecting every second, it is no different than long polling, so how do I create a PHP script that will not hang, while also sending over the SSE messages?

Naftali
  • 144,921
  • 39
  • 244
  • 303

1 Answers1

5

You seemed to have issue on php output buffering. Try adding these line to the end of your while loop:

ob_flush();
flush();

This should disable the output buffering.

EDIT You can also terminates the script after some time (i.e. 10mins) to reduce server load.

I've created a library for you to do it very easily. Check it here.

Second Edit Do you have a reverse proxy such as nginx or varnish? This may be the reason because the proxy tries to cache the content of the output but the SSE script never ends until you stop it so the whole thing hangs. Other things that captures the output may have similar results such as mod_deflate.

Third edit If you have a reverse proxy, you can try to turn off caching to allow SSE to work.

There are another ways in PHP to disable output buffering. See the code below:

<?php
for($i=0;$i<ob_get_level();$i++){
    ob_end_flush();
}
@apache_setenv('no-gzip',1);
@ini_set('implict_flush',1);
ob_implict_flush(true);
Licson
  • 2,231
  • 18
  • 26
  • 1
    This is consistent with an answer I gave to a similar question: http://stackoverflow.com/questions/7469396/how-to-implement-event-listening-in-php/8660897#8660897 – igorw Jan 02 '13 at 23:30