tags:

views:

161

answers:

3

I have a php script that is running in CLI and I want to display the current percent progress so I was wondering if it is possible to update the STDOUT to display the new percent.

When I use rewind() or fseek() it just throws an error message.

+4  A: 

Output \r and then flush to get back to the first column of the current line.

Ignacio Vazquez-Abrams
Alternately you could try using ncurses for your commandline output which has the ncurses_move(,) function which will let you put the output wherever you want, arbitrarily.
cazlab
A: 

Writing to a console/terminal is surprisingly complex if you want to move backwards in the output raster or do things like add colours - and the behaviour will vary depending on the type of console/terminal you are using. A long time ago some people came up with the idea of building an abstract representation of a terminal and writing to that.

See this article for details of how to do that in PHP.

symcbean
He already said he was using CLI.
cazlab
@cazlab: "CLI" is not a terminal type.
Ignacio Vazquez-Abrams
+3  A: 

See this code:

<?php
echo "1";
echo chr(8);
echo "2";

The output is only 2 since "chr(8)" is the char for "backspace".

So just print the amount of chars you need to go back and print the new percentage.

Printing "\r" works too on Linux and Windows but isn't going to cut it on a mac

Working example:

echo "Done: ";
$string = "";
for($i = 0; $i < 100; ++$i) {
    echo str_repeat(chr(8), strlen($string));
    $string = $i."%";
    echo $string;
    sleep(1);
}
edorian
Cheers, this answer was perfect :)
instigator
It may work with certain 7/8 bit terminal emulations but it's a messy solution
symcbean
A "messy" solution that works on every Linux (bash, shell,..) Windows and Mac Platform and doesn't require you to build ncurses (an extra php module that might not be available on your host) or something else. Everything more than this would be a waste of OPs time in at least 95% of the usecases.
edorian