How send Sever Sent Events on POST using PHP?

553 Views Asked by At

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 ?

1

There are 1 best solutions below

1
On BEST ANSWER

I'll quote straight from my SSE book, ch.9, the "HTTP POST with SSE" section:

If you bought this book just to learn how to POST variables to an SSE backend, and you’ve turned straight to this section, I’d like you to take a deep breath, and make sure you are sitting down. You see, I have some bad news. ... The SSE standard has no way to allow you to POST data to the server. This is a very annoying oversight, ...

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.)