Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a PHP script waiting "to finish script" before any echo/output?

Tags:

php

echo

Considering a simple script

<?php 
echo "hi";
foreach ($_GET['arr'] as $a)
{
 echo $a ."<br>";
}
echo "<p>Masel tov</p>";
foreach ($_GET['arr2'] as $a)
{
 echo $a ."<br>";
}

i expect the script to echo continuously. Instead the script does echo all-at-once when finished. Even the first "hi" gets echoed after 1 minute when the script finishes.

Is there a setting to prevent this from happen or why is that so?

like image 417
Email Avatar asked Feb 05 '14 17:02

Email


4 Answers

Depending on your config, output is cached until completion. You can force a flush with either ob_flush() or flush(). Sadly many modern browser also dont update until page load is complete, no matter how often you flush.

  • flush http://php.net/manual/en/function.flush.php
  • ob_flush http://php.net/manual/en/function.ob-flush.php

Configuration Settings for PHP's output buffering. http://www.php.net/manual/en/outcontrol.configuration.php

like image 186
ToBe Avatar answered Sep 22 '22 06:09

ToBe


There is a function ob_implicit_flush that can be used to enable/disable automatic flushing after each output call. But have a look at the comments on the PHP manual before using it.

like image 23
sigy Avatar answered Sep 20 '22 06:09

sigy


If you want displaying the items one by one and keep clean code that works with every server setup, you might consider using ajax. I don't like flushing the buffer unless there are no other options to accomplish the task.

If your project isn't a webproject you might consider running your code in the php console (command line) to receive immediate output.

like image 21
kasper Taeymans Avatar answered Sep 22 '22 06:09

kasper Taeymans


Check with this

if (ob_get_level() == 0)
{
    ob_start();
} 
for ($i = 1; $i<=10; $i++){
        echo "<br> Task {$i} processing ";
        ob_flush();
        flush();
        sleep(1);
}
echo "<br /> All tasks finished";
ob_end_flush();
like image 37
Jijesh Cherrai Avatar answered Sep 19 '22 06:09

Jijesh Cherrai