Yaroslav
Yaroslav

Reputation: 2438

Contiguous output in CakePHP

I have some long processing in loop and want to output progress contiguously.

while (true)
{
   $percents = $do_my_stuff();
   echo $percents;
   $this->log($percents);
}

I have tried many techniques, but still no luck

ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
while (@ob_end_flush());
ini_set('implicit_flush', true);
ob_implicit_flush(true);

flush() in each cycle

wrap loop in

$this->response->body(function () { /* loop with echo here */ }

but still browser displays all data once when script finished. Response headers:

HTTP/1.1 200 OK
Host: localhost:8765
Connection: close
X-Powered-By: PHP/5.6.20
Content-type: text/html; charset=UTF-8

PHP 5.6, built-in server using ./bin/cake server, CakePHP 3

How can i do that? I want my users see percents of operation because it can run for a long time.

Upvotes: 0

Views: 553

Answers (1)

Reactgular
Reactgular

Reputation: 54771

There is no way to enforce contiguous output to be displayed in a browser. Some browsers will not render until they've received the closing </html> tag. So to verify the output is working you need to use the network monitor to see if the server is streaming data.

Also, do not use the response object from Cake. That is used to buffer the output and have it processed by events before sending to the client. You will need to manually send the data and end the response.

header("Content-Type: text/plain");
while (@ob_end_flush()); // Flush and disable output buffers
for($a = 0; $a < 100; $a++) {
    echo "X";
    flush(); // Flush output
    sleep(1);
}
die; // end request here.

If you want to show a progress bar on the client side for a long task. This is not the way to do it.

You should write the progress to the session, save it, and then request via AJAX what that progress is.

Upvotes: 1

Related Questions