Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP echo before sleep function, not working

Tags:

php

sleep

I want output echo in browser (every time) before sleep function execute.

following code is not working

    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 str_repeat(" ", 1024);
        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 second.
Second time : Sleeping for 2 second. Sleeping for 2 second.

and continue...

is possible echo one by one without str_repeat() function, why output doesn't display every time.

like image 498
RavatSinh Sisodiya Avatar asked Dec 08 '22 16:12

RavatSinh Sisodiya


2 Answers

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(); 
}
like image 142
RavatSinh Sisodiya Avatar answered Dec 28 '22 11:12

RavatSinh Sisodiya


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

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

Second, look if mod_gzip or zlib.output_compression is turned on for example. This will also buffer all output.

If using IIS server and not Apache, there might also be settings in IIS to check.

like image 21
nl-x Avatar answered Dec 28 '22 11:12

nl-x