instigator
instigator

Reputation: 1677

Seeking STDOUT in PHP

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.

Upvotes: 8

Views: 1498

Answers (3)

edorian
edorian

Reputation: 38961

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);
}

Upvotes: 8

symcbean
symcbean

Reputation: 48357

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.

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

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

Upvotes: 4

Related Questions