php server sent events 1

php server sent events

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

while (true) {
  	$data = [
    	'name' => 'Rasmus Lerdorf'
    ]

  	echo "event: sse\n";
  	echo "data: " . json_encode($data) . "\n\n";
    echo str_pad('', 4096) . "\n";
      
	ob_flush();
  	flush();
  	sleep(1);

  	if (connection_aborted()) {
    	break;
  	}
}
ob_end_flush();

Here is what the above code is Doing:
1. We’re setting the Content-Type header to text/event-stream. This is the standard MIME type for Server-Sent Events.
2. We’re setting the Cache-Control header to no-cache. This is to prevent any caching of the response.
3. We’re sending an event named sse.
4. We’re sending the data as a JSON encoded string.
5. We’re sending a blank line to indicate the end of the event.
6. We’re flushing the output buffer and PHP’s output buffers.
7. We’re sleeping for 1 second.
8. We’re checking if the connection has been aborted. If it has, we’re breaking out of the loop.
9. We’re flushing the output buffer and PHP’s output buffers again.
10. We’re ending the output buffer.

Similar Posts