Server-sent events and php - what triggers events on the server?
The fundamental confusion surrounding Server-Sent Events (SSE) usually stems from a misunderstanding of how the HTTP connection lifecycle differs between standard requests and streaming endpoints. The core questionâhow does the server know when to send the next message without pollingâis answered by the flush() function and the persistent nature of the TCP connection, not by a continuous background thread in the traditional sense.
In the example provided from HTML5 Rocks, the PHP script sends a single timestamp and then terminates. It is crucial to recognize that this specific implementation represents a one-shot event stream, not a real-time ticker. When the browser receives that response, it parses the message and immediately closes the connection because the server has finished writing its output. This behavior mimics a standard AJAX request but uses the SSE format for transport. It is indeed functionally identical to using setInterval in JavaScript with an AJAX call; the distinction lies only in the protocol headers used.
To build a practical example like a stock ticker, you must change the logic inside stream.php. Instead of terminating after sending one message, the script must remain open for the duration of the client's session. This is achieved using an infinite loop that checks for data changes and calls flush() to push updates as soon as they happen.
Here is how the logic typically looks in a continuous streaming scenario:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastPrice = null; // Track previous price to detect changes
while (true) {
// Check if stock price has changed since last check
$currentPrice = getStockPrice();
if ($lastPrice !== $currentPrice) {
sendMsg($currentPrice);
$lastPrice = $currentPrice;
}
// Wait before checking again to prevent CPU spin
sleep(1);
}
function sendMsg($price) {
echo "data: {$price}\n";
echo "\n";
flush();
}
The mechanism here relies on the operating system maintaining the open socket. As long as the browser has not sent a disconnect signal, the PHP process remains active. The sleep() function is critical; without it, the script would spin in a tight loop, consuming 100% CPU and potentially exhausting server resources before any actual data change occurs.
However, this approach introduces significant scalability challenges that you must consider. If your application runs on a standard PHP-FPM or Apache setup, every concurrent user holding an open stream to stream.php effectively occupies a persistent worker process. Unlike a request-response cycle where the worker finishes and is reused, these streams prevent the server from handling other requests while waiting for data updates.
If you have thousands of users watching a stock ticker simultaneously, you will eventually hit your PHP process limit or exhaust available file descriptors. This is why high-performance applications often move SSE logic into a separate backend service written in a language better suited for concurrent I/O, such as Go, Node.js, or a message queue system like Redis or RabbitMQ. The PHP script can fetch updates from that external source rather than polling a database directly, offloading the heavy lifting and managing the connection state more efficiently.
You know it is time to end an instance of stream.php when the client explicitly requests a disconnection. In SSE, this happens if the browser loses network connectivity or if the JavaScript code calls source.close(). The server detects this via the underlying socket closing event, which causes the PHP script to exit its loop and terminate gracefully. There is no need for complex logic to determine "when" to stop; the termination is driven entirely by the state of the network connection.