In a website I am buiding, I have a section that lists notifications, which are just pages created in the panel. When a new notification page is published, I want the event to be reflected live on the website.
I found that server-sent events is probably a potential solution for performing the above.
I followed the tutorial on Using server-sent events - Web APIs | MDN, which luckily, has a php example.
Their example code:
header("Cache-Control: no-store");
header("Content-Type: text/event-stream");
$counter = rand(1, 10);
while (true) {
echo "event: ping\n";
$curDate = date(DATE_ISO8601);
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";
$counter--;
if (!$counter) {
echo 'data: This is a message at time ' . $curDate . "\n\n";
$counter = rand(1, 10);
}
ob_end_flush();
flush();
if (connection_aborted()) break;
sleep(1);
}
My problem is that I can’t manage to integrate this in Kirby. I tried using the code inside a route to be called by javascript, but the server responses are arriving slowly (the responses are staying in a pending state for a while). The same happens if I use the code in a template file.
Perhaps the php code should be in a file outside of Kirby? Calling the external php file (residing in the site’s root folder) from javascript results in kirby ‘page not found’ errors.
Is there a way to call a .php file external to Kirby? And if there is, how could I get Kirby content (the notification pages) inside it?