Skip to content

Instantly share code, notes, and snippets.

@Kubo2
Created November 19, 2019 19:10
Show Gist options
  • Save Kubo2/8f68b246b367c90dbf9631c9564d05f5 to your computer and use it in GitHub Desktop.
Save Kubo2/8f68b246b367c90dbf9631c9564d05f5 to your computer and use it in GitHub Desktop.
Jednoduchá realtime aplikácia so serverovým úložiskom a server-sent events
<!doctype html>
<title>Načítava sa...</title>
<h1>Meno teraz je <span id='name'></span></h1>
<script>
const span = document.getElementById('name');
const es = new EventSource('onChange.php');
es.onmessage = function (msg) {
span.innerText = document.title = msg.data;
};
</script>
<?php
const FILE = __DIR__ . '/name.txt';
if(!empty($_POST['name'])) {
$name = $_POST['name'];
file_put_contents(FILE, $name);
}
$escName = htmlspecialchars($name ?? file_get_contents(FILE)); // ošetrí výpis > < " do HTML
?>
<!doctype html>
<title>Zmeniť meno: <?= $escName ?></title>
<h1><?= $escName ?></h1>
<form method='post'>
<textarea name='name'><?= $escName ?></textarea>
<input type="submit" value="Ulož nové meno">
</form>
<?php
ob_end_clean();
set_time_limit(0);
const FILE = __DIR__ . '/name.txt';
header('Connection: keep-alive');
header('Cache-Control: no-cache');
header('Content-Type: text/event-stream; charset=UTF-8');
while(TRUE) {
clearstatcache();
if(isset($lastRetrieved) && $lastRetrieved >= filemtime(FILE)) {
continue;
}
$cachedName = file_get_contents(FILE);
$lastRetrieved = time();
printf("data:%s\n\n", $cachedName); // SSE event
flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment