PHP Output with Sleep()

PHP output text before sleep

check this out

<?php

ob_start();

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

?>

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 echo before sleep function, not working

Try following code and its work.

header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
set_time_limit(0);
ob_implicit_flush(1);
//apache_setenv('no-gzip', 1);
//ini_set('zlib.output_compression', 0);
//ini_set('implicit_flush', 1);
for ($i = 0; $i < 10; $i++) {
$randSlp=rand(1,3);
echo "Sleeping for ".$randSlp." second. ";;
sleep(1);
if(ob_get_level()>0)
ob_end_flush();
}

How sleep() works in PHP

You need to use the flush function of PHP, to get the excepted result.

PHP gives you the output, when script has finished. If you want to show the result in real time, you need to flush the output buffer.

$time_now = time();
echo "Time Now : " . $time_now;
flush();
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;

PHP: sleep() for particular line of code

You want to use AJAX for this. Example using jQuery:

<div id="content">
<-- You want to load something here after 5 seconds -->
</div>

<script type="text/javascript">
setTimeout(function() {
$('#content').load("/url/to/your/script.php");
}, 5000); // 5000 is the time to wait (ms) -> 5 seconds
</script>

This would load the output (echo) of script.php into the div with the ID "content". By doing it this way, you let the client do all the rendering work as already recommended by @GhostGambler

This will not block outputting other content sent by the initial script.



Related Topics



Leave a reply



Submit