Search code examples
javascriptphpbufferserver-sent-events

Ob_end_flush is generating constant errors


I am currently working with Server-Sent Events and I am having a strange issue. As the event goes on, through each iteration I am receiving the following error:

ob_end_flush(): failed to delete and flush buffer. No buffer to delete or flush in

My code for the Server-Event Server Side is as follows:

<?php

  require "connect.php";

  session_write_close();

  header("Content-Type: text/event-stream\n\n");

  $savedcount = 0; 
  while (1) {

    // Who's mechanism 
    $query = $mysqli->query("SOME QUERY"); 
    $rowcount = $query->num_rows;

    if ($savedcount != $rowcount) {
       // echo stuff
       $savedcount = $rowcount; // only echo stuff if there is new content
    }

    ob_end_flush();
    flush();
    sleep(2);
  }

?>

I do not completely understand buffers. Also, before you assume that this is terrible practice please know that Server-Sent Events are special. This is a similar script that they show on MDN. For this reason I am not exactly sure why I am continuously receiving these errors.

Suggestions?


Solution

  • I have always used this idiom:

    @ob_flush();@flush();
    

    Quoting from p.21 of Data Push Apps With HTML5 SSE: (disclaimer: my book)

    @ is said to be slow. But putting that in context, it adds on the order of 0.01ms to call it twice, as shown here. ... http://git.php.net/?p=php-src.git;a=blob;f=sapi/apache2handler/sapi_apache2.c#l290 suggests flush() can never throw an error, so @ on flush() could be dropped, just leaving it on @ob_flush().

    http://git.php.net/?p=php-src.git;a=blob;f=main/output.c#l1328 shows the two E_NOTICEs that ob_flush() can give.