I'm just starting with PHP and Server Sent Events. After checking out a couple of articles,like the W3C and HTML5Rocks one I was able to get something off the ground very fast.
What I'm trying to do now is sending a Server Sent Event when my php script receives a POST. Here's what my naive attempt looks like:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'POST') {
$serverTime = time();
$data = file_get_contents("php://input");
sendMsg($serverTime,$data);
}
?>
This doesn't seem to work, but I can't work out why. I can't see any errors and using JS I can see a client can connect, but no data comes through when performing a POST action.
What's the recommended way of sending a Server Sent Event when a server receives a POST ?
I'll quote straight from my SSE book, ch.9, the "HTTP POST with SSE" section:
The alternative is to go back to the pre-SSE alternatives (because
XMLHttpRequest
, i.e. AJAX, does allow POST); the book does cover that in quite some detail.Actually, there is one other workaround, that is actually rather easy given that you are using PHP: first post the data to another script, use that to store your POST data in
$_SESSION
, and then have your SSE script get it out of$_SESSION
. (That is not quite as ugly as it sounds: the SSE process is going to be long-running, so one extra http call to set it up is acceptable.)