sse_tester.php
64 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['PHPINFO'] ) ) { |
| 11 | phpinfo(); |
| 12 | } |
| 13 | else if ( isset( $_GET['SSE'] ) ) { |
| 14 | |
| 15 | // Set the headers for SSE. |
| 16 | header( 'Cache-Control: no-cache' ); |
| 17 | header( 'Content-Type: text/event-stream' ); |
| 18 | header( 'X-Accel-Buffering: no' ); // This is useful to disable buffering in nginx through headers. |
| 19 | |
| 20 | // Push data to the browser every second. |
| 21 | ob_implicit_flush( true ); |
| 22 | ob_end_flush(); |
| 23 | for ( $i = 0; $i < 3; $i++ ) { |
| 24 | $data = "data: $i"; |
| 25 | echo $data . "\n\n"; |
| 26 | if ( ob_get_level() > 0 ) { |
| 27 | ob_flush(); |
| 28 | } |
| 29 | flush(); |
| 30 | error_log( $data ); |
| 31 | sleep( 1 ); |
| 32 | } |
| 33 | echo "data: Done!\n\n"; |
| 34 | } |
| 35 | else { |
| 36 | ?> |
| 37 | <h1>Stream / SSE</h1> |
| 38 | <p> |
| 39 | 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. |
| 40 | </p> |
| 41 | <h2>Output:</h2> |
| 42 | <ul id="results"></ul> |
| 43 | <button onclick="window.location.reload();">Retry</button> |
| 44 | <script> |
| 45 | var url = window.location.href; |
| 46 | var source = new EventSource(url + "?SSE=true"); |
| 47 | |
| 48 | source.onmessage = function(event) { |
| 49 | if (event.data == 'Done!') { |
| 50 | source.close(); |
| 51 | } |
| 52 | else { |
| 53 | document.getElementById("results").innerHTML += "<li>" + event.data + "</li>"; |
| 54 | console.log(event); |
| 55 | } |
| 56 | }; |
| 57 | |
| 58 | source.onerror = function(event) { |
| 59 | console.error(event); |
| 60 | }; |
| 61 | </script> |
| 62 | <?php |
| 63 | } |
| 64 |