Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement Server Sent Events in PHP?

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?

like image 850
Naftali Avatar asked Jan 02 '13 22:01

Naftali


People also ask

How are server-sent events implemented?

A connection over Server-Sent Events typically begins with client-initiated communication between client and server. The client creates a new JavaScript EventSource object, passing the URL of an endpoint to the server over a regular HTTP request. The client expects a response with a stream of event messages over time.

How do I send events from server to client?

The server-sent events streaming can be started by the client's GET request to Server. Accept: text/event-stream indicates the client waiting for event stream from the server, Cache-Control: no-cache indicates that disabling the caching and Connection: keep-alive indicates the persistent connection.

Which element is required for server-sent events?

To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document. The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events.


1 Answers

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);
like image 67
Licson Avatar answered Sep 28 '22 04:09

Licson