Php echo before sleep function not working

I want the output echo in the browser (every time) to be executed before the sleep function is executed.

the following code does not work

set_time_limit(0); ob_implicit_flush(1); ob_start(); echo "Start<Br>"; ob_flush(); for($i=0;$i<10;$i++){ $randSlp=rand(1,3); echo "Sleeping for ".$randSlp." second. "; ob_flush(); sleep($randSlp); } ob_end_flush(); 

if uncomment str_repeat function than in browser
First time: Start Sleeping for 1 second. Sleeping for 3 seconds.
Second time: sleep 2 seconds. Sleeping for 2 seconds.

and continue ...

maybe echo one by one without str_repeat () function, why the output is not displayed every time.

+4
source share
2 answers

Try the 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(); } 
+11
source

even the output buffer (ob_ * functions) does not necessarily give output to the browser directly.

First try calling flush() before or after ob_flush() .

Secondly, see for example if mod_gzip or zlib.output_compression is enabled. This will also buffer the entire output.

If you are using an IIS server rather than Apache, there may also be settings in IIS for verification.

+1
source

All Articles