Trying to implement Server Side Events – On the server side (php), the below while loop doesn’t catch when the session is changed from another php script. It does catch it when the whole web page is reloaded. The second code without the loop catches the session change. Any clues to why and how to handle?
Not working code
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
function sendEvent($event, $data) {
echo "event: $eventn";
echo "data: $datann";
ob_flush();
flush();
}
// Check signing status and send events
while (true) {
session_start(); // Reopen the session to get the latest data
$status = $_SESSION['signing_status'];
session_write_close(); // Immediately close the session to avoid locks
sendEvent("event",$status);
// Wait for a few seconds before checking again
sleep(4);
}
?>
Working code
<?php
session_start();
$status = $_SESSION['signing_status'];
session_write_close();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$eventId = 0; // Initialize event ID
sendEvent("event", $_SESSION['signing_status']);
function sendEvent($event, $data) {
echo "event: $eventn";
echo "data: $datann";
ob_flush();
flush();
}
?>