Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

PHP can be used to implement Server-Sent Events by using the following steps:

  1. Set the content type of the response to text/event-stream.

  2. Create an infinite loop that sends data to the client at a regular interval.

  3. Use the flush() function to send the data immediately to the client.

  4. Use the sleep() function to delay the response and prevent the server from overwhelming the client with too much data.

  5. Set an "event" field in the data to specify the type of event being sent.

  6. Add a "retry" field in the data to specify the time interval in milliseconds after which the client should re-establish the connection if the connection is lost.

For example, the following PHP code creates an SSE endpoint that sends a random number to the client every second:

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

while (true) {
  $data = array(
    'event' => 'randomNumber',
    'data' => rand(1, 100),
    'retry' => 1000
  );

  echo 'data: ' . json_encode($data) . "\n\n";
  flush();
  sleep(1);
}

The data sent to the client is in JSON format and includes the "event" field to specify the type of data being sent. The "retry" field is set to 1000 milliseconds, indicating that the client should retry connecting to the server after a one-second delay if the connection is lost.