Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top