Hello,
This post is very brief and a quick tip.
In this age where Ajax has taken over as preferred method for background tasks there are many a time that we still have heavy ended loops that holds the page load till they finish their execution. Well! normal scenarios is when we do reports stuff.
1
|
ob_implicit_flush(true);
|
So your script will look like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
ob_implicit_flush(true);
ob_implicit_flush(true);
for($i=0;$i<100;$i++) { // do stuff $result = reports_function(); // this takes time echo $result; // $result will be flushed automatically }
for($i=0;$i<100;$i++) {
// do stuff
$result = reports_function();
// this takes time
echo $result;
// $result will be flushed automatically
}
?>
|
But as per some reports such as this one
The above method may not work. But the one that I use is the one given below
Preferred way
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
ob_start();
for($i=0;$i<100;$i++) {
// do stuff
$result = long_running_function();
// this takes time
echo $result;
ob_end_flush();
ob_flush();
// $result will be flushed automatically
}
?>
|
As you can see that I’ve called ob_start() as the first line of above example. ob_start() will enable the output buffering for our page.
Then you see that I am using function ob_end_flush() and flush() after the echo function.
This means that whatever is in the current output buffer, flush it.
Thus whatever is printed will appear on your browser.
Excercise
Copy paste this code into a new file called test.php and save it to the root of your test website’s root folder and then run it from browser to see if it works.
1
2
3
4
5
6
7
8
9
|
<?php
ob_start();
for($i=0;$i<9;$i++) {
echo $i.'<br>';
ob_end_flush();
ob_flush();
sleep(1);
}
?>
|
Lot of people would have loads of problems with this stuff. Its your webserver that has to be set correctly and even then the code above may not work.
If the above does not work then its work add the header to the start of the script as shown below
1
2
3
4
|
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("Expires: Mon, 24 Sep 2012 04:00:00 GMT");
|
Above should print 0 till 9 and with each increment you will notice a delay of 1 second.
I hope this helps.