Skip to content

Instantly share code, notes, and snippets.

@k4ml
Last active October 11, 2016 03:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save k4ml/781dbf0c9c78a20eabbb to your computer and use it in GitHub Desktop.
Save k4ml/781dbf0c9c78a20eabbb to your computer and use it in GitHub Desktop.
PHP SSE Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
var source = new EventSource('updates.php');
source.onmessage = function(e) {
var updates;
updates = e.lastEventId + ':' + e.data + '<br>';
document.body.innerHTML += updates;
};
</script>
</body>
</html>
<?php
/*
Create table as:-
create table data (id integer primary key, message varchar)
Then to see the update on browser, insert new message:-
insert into data (message) values ('hello');
...
insert into data (message) values ('second');
*/
$db = new SQLite3('data.db');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
function send_msg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
// in the event of client reconnect, it will send Last-Event-ID in the headers
// this only evaluated during the first request and subsequent reconnect from client
$last_event_id = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : False);
if ($last_event_id == 0) {
$last_event_id = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : False);
}
// also keep our own last id for normal updates but favor last_event_id if it exists
// since on each reconnect, this value will lost
$last_id = 0;
while (1) {
error_log('$last_id:' . $last_id, 4);
error_log('$last_event_id:' . $last_event_id, 4);
$id = $last_event_id != False ? $last_event_id : $last_id;
$stm = $db->prepare("SELECT id, message FROM data WHERE id > :id");
$stm->bindValue('id', $id);
$results = $stm->execute();
if ($results) {
while ($row = $results->fetchArray()) {
if ($row) {
send_msg($row['id'], $row['message']);
$last_id = $row['id'];
}
}
}
sleep(5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment