Search code examples
phpparameter-passingserver-sent-eventsevent-stream

Passing data from PHP script to PHP Event Stream


So I have a PHP file that will randomly receive new posted data from a third-party. For the sake of simplicity, let's call it get_data.php and say it looks something like this:

<?php
$data = $_REQUEST;
// Data processing

And then I have a separate script, stream.php, which is using HTML5 Server-Sent Events to stream data to a (JS) client:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (true) {
    echo 'data: ' . $data . PHP_EOL;
    echo PHP_EOL;
    ob_flush();
    flush();
    sleep(1);
}

Each script by itself is working fine. However, I need to pass the $data from the first script to the second one.

I know I can achieve this by storing the variable in a DB or temp file, but ideally I'd be able to do this by means of PHP alone.

Including one file inside the other doesn't look like a good option either because the stream headers are likely to mess things up with the third-party posting the data, and I'd like to keep the data processing separate from the stream in case the latter crashes.

NOTE - This is not a duplicate of other questions asking how to pass data between PHP scripts on a webpage, given that I seemingly cannot use $_SESSION variables as the data is posted by a third-party different than the user accessing the event stream.


Solution

  • You could use shared memory to pass data between to discrete scripts. http://php.net/manual/en/intro.sem.php

    This will require both scripts are running on the same physical machine/vm, and you will need to determine a way of identifying which shared memory blocks are for which session.

    You could combine this with the system message queues to signal when (and perhaps where) new data has arrived. Although be careful as these are implemented with different limits on Linux/BSD/Unix systems (MacOS has some annoying limitations that Linux doesn't)

    HTH