sse_tester.php
61 lines
| 1 | <?php |
| 2 | |
| 3 | // Various links |
| 4 | // https://serverfault.com/questions/488767/how-do-i-enable-php-s-flush-with-nginxphp-fpm |
| 5 | // https://stackoverflow.com/questions/72394213/nginx-configuration-for-server-sent-event |
| 6 | // https://serverfault.com/questions/801628/for-server-sent-events-sse-what-nginx-proxy-configuration-is-appropriate |
| 7 | // https://qiita.com/okumurakengo/items/cbe6b3717b95944083a1 (in Japanese) |
| 8 | |
| 9 | // If '?SSE' is set, send Server-Sent Events, otherwise we'll display the page. |
| 10 | if ( isset( $_GET['SSE'] ) ) { |
| 11 | |
| 12 | // Set the headers for SSE. |
| 13 | header( 'Cache-Control: no-cache' ); |
| 14 | header( 'Content-Type: text/event-stream' ); |
| 15 | header( 'X-Accel-Buffering: no' ); // This is useful to disable buffering in nginx through headers. |
| 16 | |
| 17 | // Push data to the browser every second. |
| 18 | ob_implicit_flush( true ); |
| 19 | ob_end_flush(); |
| 20 | for ( $i = 0; $i < 3; $i++ ) { |
| 21 | $data = "data: $i"; |
| 22 | echo $data . "\n\n"; |
| 23 | if ( ob_get_level() > 0 ) { |
| 24 | ob_flush(); |
| 25 | } |
| 26 | flush(); |
| 27 | error_log( $data ); |
| 28 | sleep( 1 ); |
| 29 | } |
| 30 | echo "data: Done!\n\n"; |
| 31 | } |
| 32 | else { |
| 33 | ?> |
| 34 | <h1>Stream / SSE</h1> |
| 35 | <p> |
| 36 | I build this code in order to experiment with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">SSE</a> with PHP as it seems to be tricky to make it work. This idea is that the events below appear every one second, and not all at once. |
| 37 | </p> |
| 38 | <h2>Output:</h2> |
| 39 | <ul id="results"></ul> |
| 40 | <button onclick="window.location.reload();">Retry</button> |
| 41 | <script> |
| 42 | var url = window.location.href; |
| 43 | var source = new EventSource(url + "?SSE=true"); |
| 44 | |
| 45 | source.onmessage = function(event) { |
| 46 | if (event.data == 'Done!') { |
| 47 | source.close(); |
| 48 | } |
| 49 | else { |
| 50 | document.getElementById("results").innerHTML += "<li>" + event.data + "</li>"; |
| 51 | console.log(event); |
| 52 | } |
| 53 | }; |
| 54 | |
| 55 | source.onerror = function(event) { |
| 56 | console.error(event); |
| 57 | }; |
| 58 | </script> |
| 59 | <?php |
| 60 | } |
| 61 |