How can PHP handle server-side events and notify clients without relying on AJAX?
PHP can handle server-side events and notify clients without relying on AJAX by using server-sent events (SSE). SSE allows servers to push data to web clients over a single, long-lived connection. This eliminates the need for constant client requests and reduces server load. To implement SSE in PHP, you can use the `header()` function to set the content type to `text/event-stream` and then continuously output data to the client using `echo`.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Simulate server-side events
for ($i = 0; $i < 10; $i++) {
echo "data: Event $i\n\n";
ob_flush();
flush();
sleep(1); // Simulate delay between events
}
?>