0

As the title, I have a script with some functions, when i run that file (on webserver), it will wait all functions to be finished then display all result at one time to screen. I just want to run a function and display its result then do next functions. Example:

<?php
function Fun1(){
echo 'Done 1st func';
sleep(3); //This is run time of Func1
}
function Fun2(){
echo 'Done 2nd func';
sleep(3); //This is run time of Func2
}
function Fun3(){
echo 'Done 3rd func';
}
?>

Then result will be displayed first as:

Done 1st func

After 3s loadtime of Func1, another line added:

Done 2nd func

After 3s loadtime of Func2

Done 3rd func

NOT like that (after 6s wait time):

Done 1st func
Done 2nd func
Done 3rd func

Thanks in advance :)

David Mcintyre
  • 60
  • 1
  • 12

1 Answers1

2

You did not specified if you will run the script in the command line or on a web server. But since running it in the CLI is already producing output as it happens, I will assume that you will be going to use it with Apache.

In order to have the output displayed immediately when it happens you will need to clear the PHP's output buffers and flush the output immediately.

Here is an example:

<?php
while(ob_get_level()) ob_end_clean();
ob_implicit_flush(true);

function Fun1(){
    echo 'Done 1st func';
    sleep(3); //This is run time of Func1
}
function Fun2(){
    echo 'Done 2nd func';
    sleep(3); //This is run time of Func2
}
function Fun3(){
    echo 'Done 3rd func';
}
?>

Note: This will work as long as PHP is installed as an Apache module. You can check that in phpinfo();. If it's installed as CGI Handler or FastCGI then you will have to disable the output buffers for those too.

Ibrahim
  • 1,876
  • 11
  • 19
  • I run it on Nginx webserver and ouput via browser :( Seem like it doesn't work on Nginx. – David Mcintyre Feb 09 '17 at 09:03
  • You may need to search how to do that on nginx. Here is something that may be worth checking: http://stackoverflow.com/questions/12165810/how-to-disable-output-buffering-in-nginx-for-php-application – Ibrahim Feb 09 '17 at 09:10
  • Hi @lbrahim do you know how to limit the time of each loop can run? example: `code` $i=0; while(1) { sleep($i); $i++ } , if a turn run more than 5s then break it and continue looping... – David Mcintyre Feb 09 '17 at 10:29
  • Kinda tricky without using threads. You can try using `set_time_limit()` inside your functions since that supports local scopes. If that doesn't work for you, then you're out of luck. Note that the sleep function will not count against time limit, so you need other test scenarios without sleep. – Ibrahim Feb 09 '17 at 11:05