No Flush In Loop
ID |
php.no_flush_in_loop |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Php |
Tags |
efficiency, loop |
Description
Reports a call to an output-flushing function (flush, ob_flush) inside a loop body.
Flushing on every iteration sends the response to the client in many tiny chunks instead of
one efficient block.
Rationale
flush() and ob_flush() push whatever has been buffered so far out to the web server and on
to the client. Calling them once per iteration forces the server, and often the network and the
browser, to handle a large number of small writes — each with its own overhead. Building the
output during the loop and flushing a single time after it finishes does the same work with a
fraction of the system calls.
<?php
foreach ($rows as $row) {
echo render($row);
flush(); // FLAW — flushes the buffer on every iteration
}
foreach ($rows as $row) {
echo render($row);
}
flush(); // OK — flushed once, after the loop
Remediation
Move the flush() / ob_flush() call out of the loop so the buffered output is flushed once
after the loop completes. Flush inside the loop only when you genuinely need incremental
streaming (for example a long-running progress feed), and then consider flushing in batches.