Php: Output Data Before and After Sleep()

PHP: Output data before and after sleep()?

faileN's answer is correct in theory. Without the ob_flush() the data would stay in PHP's buffer and not arrive at the browser until the buffer is implicitly flushed at the end of the request.

The reason why it still doesn't work is because the browsers also contain buffers. The data is now sent out correctly, but the browser waits after getting "one" before it actually kicks off rendering. Otherwise, with slow connections, page rendering would be really, really slow.

The workaround (to illustrate that it's working correctly) is, of course, to send a lot of data at once (maybe some huge html comment or something) or to use a tool like curl on the command line.

If you want to use this sending/sleeping cycle for some status update UI on the client, you'd have to find another way (like long-polling and AJAX)

PHP output text before sleep

check this out

<?php

ob_start();

echo 'Output one.';
ob_flush();
usleep(1500000);
echo 'Output two.';
ob_flush();

?>

PHP AJAX echo json data before then sleep

Most likely the echo'd data is just being buffered rather than sent until sleep finishes and the request completes. Try using flush() to force pushing the output to the client:

echo json_encode($return);
flush();
sleep(7);
die();

If this fails, you may find padding the output will help meet the server/browser's minimum length requirement to flush/display the data:

echo str_pad(json_encode($return),8192," ");
flush();
sleep(7);
die();


Related Topics



Leave a reply



Submit