0

I'm experimenting here with output buffering and am stuck on carriage returns, overwrites.

Basically, if I run this snippet in CLI:

<?php

$times = 5000;

for ($i = 1; $i <= $times; $i++)
{
    echo chr(13) . sprintf('Running step %d/%d...', $i, $times);
}

It will stay on line 1 and overwrite the contents with actual step information.

Like, on first step the console output will be:

> php micro.php
Running step 1/5000...

On step 3333:

> php micro.php
Running step 3333/5000...

After completition:

> php micro.php
Running step 5000/5000...
>

As you can see, in total, the program will have only consumed 1 line for it's output.

Now, if I tweak the script for browser and request it from browser:

<?php

header('Content-Type: text/plain; charset=iso-8859-1');

$times = 50000;

for ($i = 1; $i <= $times; $i++)
{
    echo chr(13) . sprintf('Running step %d/%d...', $i, $times);
    flush();
    ob_flush();
}

I get the output while the script is being processed, but, it is not overwritten.

Like, on first step the console output will be:

localhost/micro.php:

Running step 1/5000...

On step 3333:

localhost/micro.php:

Running step 1/5000...
Running step 2/5000...
Running step 3/5000...
Running step 4/5000...
...
Running step 3333/5000...

After completition:

localhost/micro.php:

Running step 1/5000...
Running step 2/5000...
Running step 3/5000...
Running step 4/5000...
...
Running step 3333/5000...
...
Running step 5000/5000...

In total consuming 5001 lines.

How do I carriage return in a browser output to force line overwrite?

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • I do not understand your requirements. Could you explain more clearly what you are trying to do ? – LeGEC Aug 28 '13 at 12:22
  • 1
    You will not 'get output while script is being processed'. HTTP is synchronous - so you'll see only full executed script result – Alma Do Aug 28 '13 at 12:23
  • @LeGEC see update. And, Alma, yes you will, if you explicitly flush it. – tomsseisums Aug 28 '13 at 12:30

2 Answers2

1

As far as I know, you can't.

The only way I see to implement a progress bar in a browser involves javascript, and ajax requests to poll the server on the progress status.

LeGEC
  • 46,477
  • 5
  • 57
  • 104
0

There's some kind of workaround: On every iteration/operation you can flush javascript which overwrites text inside html element.

You can see the example progressbar in my test app: http://darium.linuxpl.eu/tag/ - to see the progressbar you should upload any csv file and click "generuj"

Dariusz Majchrzak
  • 1,227
  • 2
  • 12
  • 22