Ask Your Question
2

How can PHP be used to implement Server-Sent Events?

asked 2022-12-27 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-05-09 01:00:00 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-27 11:00:00 +0000

Seen: 20 times

Last updated: May 09 '21