Question

I just started using SSE in my PHP pages. I can very easy send new data with this code:

while(true) {
    if (isset($_GET["selectedName"]) && $_GET["selectedName"] != "empty") {
        echo "data:current timestamp for user ".$_GET["selectedName"]." is ".time().PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }
    sleep(1);
}

But this means, that I'm sending data every second to the client and I have to run a loop. The string in the example is not much data. But later I want to connect to a database and pull stuff from there.

If I would pull something like a whole article (or message or what ever), I would produce a very big amount of data.

Now my question: How can I tell script to provide new data and send it to the client from another PHP script?

I created a little iOS app which uses a small API to send status updates to the server. I'd like one of the API scripts to tell the web interfaces event source script to send the new data.

And only, when I tell it to do so. How can I achieve this?

Thanks for help, with kind regards, Julian

Was it helpful?

Solution

Regarding the fact I don't have MUCH stuff to send at once (a state number from 0 to 4 and a little message string), I decided to set a variable and check if anything changed:

static $oldStateString;

while(true) {
    $result = mysql_query("SELECT * FROM st_workers");
    $currentStateString = "";

    while ($user = mysql_fetch_array($result)) {
        $currentStateString .= $user["stateIndex"].":--;".$user["state"].":--;".$user["humanReadableName"].":__;";
    }

    if ($currentStateString != $oldStateString) {
        echo "data:".$currentStateString.PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();

        $oldStateString = $currentStateString;
    }
    sleep(1);
}

BUT: I noticed that you have to start to event handler a little later, not <body onload="">. This produces errors in most browsers except Safari 6 and the current FireFox. The browser doesn't recognize that it's not loading anymore. So the "loading spinner" does not stop until like 5 minutes or more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top