Question

I faced a strange issue today.

For several months I used buffer flushing in PHP to send small string sizes to the client without problems.

Today I returned to the project and it turned out that my server won't send strings smaller than 512 bytes.

Here is my code:

<?php
    echo "length:".$myUpcomingStringSize;
    ob_flush();
    flush();

    sleep(1);

    for($i = 0; $i < count($allLines); $++) {
        echo $allLines[$i];
        ob_flush();
        flush();
    }
?>

This code worked like charm the whole last year. And now it doesn't anymore. I played around a bit and added some random characters. As the string size gets equal or greater 512, the server sends the buffer content.

Can anybody imagine the issue I have to solve here? Anyone else facing this issue? Or does someone know how to configure this minimum packet size?

Was it helpful?

Solution

If you changed neither the program nor the server, you should assume that the program never worked as intended. Especially Windows systems are known to buffer the output until a certain number of Bytes is in the output buffer. This buffering is at system-level and thus can not be affected by any PHP configuration.

If you know that 512 Bytes is the minimum required for the output buffer to send, then you could use something like

define('MIN_OUTPUT_LENGTH', 512);
echo str_pad("length: $myUpcomingStringSize", MIN_OUTPUT_LENGTH, "\0"), '\n';
// (If you run into trouble with the null-bytes, use space character instead)

Notes

  • If you do not use "userspace" output buffering, then ob_flush(); is redundant.
  • If there is no delay in your for loop, then flushing between lines is not a good idea. Especially for mobile applications where the network tries to pack as much data as possible into a single packet.
  • There is a syntax error in your for loop header (The expression $++ is missing a variable identifier, probably i)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top