Skip to content

Instantly share code, notes, and snippets.

@g105b
Created January 21, 2019 16:15
Show Gist options
  • Save g105b/8bce1da26279bb9c7f07ca61bfeda50f to your computer and use it in GitHub Desktop.
Save g105b/8bce1da26279bb9c7f07ca61bfeda50f to your computer and use it in GitHub Desktop.
SSE
<?php
header("Access-Control-Allow-Origin: *");
$accept = $_SERVER["HTTP_ACCEPT"];
if($accept === "text/event-stream") {
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
$i = 0;
while($i < 10) {
$time = time();
echo "id: $time\n";
echo "event: gregupdate\n";
echo "data: {message: \"test\"}\n";
echo "\n";
flush();
ob_flush();
sleep(1);
$i++;
}
exit;
}
if(!empty($_POST)) {
$msg = $_POST["message"] ?? null;
if($msg) {
file_put_contents("messages.txt", $msg . PHP_EOL, FILE_APPEND);
header("Location: /");
exit;
}
}
$msgList = [];
if(is_file("messages.txt")) {
$msgList = file("messages.txt");
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>SSE test</title>
</head>
<body>
<div id="output" style="white-space: pre">
<?php
foreach($msgList as $msg) {
echo $msg . PHP_EOL;
}
?>
</div>
<form method="post">
<input name="message" placeholder="Message" />
<button>Submit</button>
</form>
<script>
let source = new EventSource(location.href);
source.onmessage = function(event) {
console.log(event);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment