Server Sent Events PHP Example

by Wayne Smith

Time sent from server

Server-Sent Events (SSE) provide real-time communication from a server to the client, (note: WebSockets are bidirectional). They are useful to keep the client updated on a process that has begun on the server; or provide streaming updates for information the server can provide such as sports scores, stock updates, or even a chat feed. The benefit of real-time SSE over polling is a reduction of lag time, caused by delays in creating new connections and delays to request new data.

SSE on the browser

Nothing needs to be installed on the client/browser SSE is supported by all modern browsers; The browser needs to make a request for SSE simply by using the browser's built in API and listen.


var source = new EventSource('/events/time.php');
source.onmessage = function(e) {
// do something with e.data sent by server
};

SSE on the server

The server needs to send the correct content type to stream the data to the client, and the output for the stream needs to not be buffered. Servers may buffer the output by default in either or all: PHP, PHP gzip, apache or apache gzip, et la.


<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<180; $i++){

$time = date('r');
echo "data: {$time}\n\n";
// depending of how server and network is setup flushing the buffer with php can be different.
// for this reason and others a mircoservice or mod_proxy_fcgi is the best way to provide the stream.
echo str_pad('',8196)."\n";

ob_flush();
flush();
sleep(1);
}

ob_end_flush();
?>