Controlling cursor position in PHP CLI applications (and others)

I realized that this is still a frequently asked question on forums – how do I move the cursor in my PHP console application? The simplest way to do it in Unix based systems is to echo the terminal control escape sequence. This will work for any application or script capable of printing to the terminal.
For example, to move the cursor up 2 lines you would do:

echo "\033[2A";

So, if you want to create a simple counter:

for ($i = 1; $i < 11; $i++) {
    echo "$i\n";
    sleep(1);
    echo "\033[1A";
}

For the full list of the terminal control codes (escape sequences) for cursor and other features, like color – refer to this link:
http://www.termsys.demon.co.uk/vtansi.htm#cursor

If you need more comprehensive solution – take a look at ncurses library:
http://php.net/manual/en/book.ncurses.php

Leave a Reply

Your email address will not be published. Required fields are marked *