views:

118

answers:

1

I want to read a single character at-a-time from the command line in PHP, however it seems as though there is some kind of input buffering from somewhere preventing this.

Consider this code:

#!/usr/bin/php
<?php
echo "input# ";
while ($c = fread(STDIN, 1)) {
    echo "Read from STDIN: " . $c . "\ninput# ";
}
?>

Typing in "foo" as the input (and pressing enter), the output I am getting is:

input# foo
Read from STDIN: f
input# Read from STDIN: o
input# Read from STDIN: o
input# Read from STDIN: 

input# 

The output I am expecting is:

input# f
input# Read from STDIN: f

input# o
input# Read from STDIN: o

input# o
input# Read from STDIN: o

input# 
input# Read from STDIN: 

input# 

(That is, with characters being read and processed as they are typed).

However, currently, each character is being read only after enter is pressed. I have a suspicion the TTY is buffering the input.

Ultimately I want to be able to read keypresses such as UP arrow, DOWN arrow, etc.

Thanks in advance!

+2  A: 

The solution for me was to set -icanon mode on the TTY (using stty). Eg.:

stty -icanon

So, the the code that now works is:

#!/usr/bin/php
<?php
system("stty -icanon");
echo "input# ";
while ($c = fread(STDIN, 1)) {
    echo "Read from STDIN: " . $c . "\ninput# ";
}
?>

Output:

input# fRead from STDIN: f
input# oRead from STDIN: o
input# oRead from STDIN: o
input# 
Read from STDIN: 

input# 

Props to the answer given here:
http://stackoverflow.com/questions/3315538/is-there-a-way-to-wait-for-and-get-a-key-press-from-a-remote-terminal-session/3315627#3315627

For more information, see:
http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92

P.S. Don't forget to reset the TTY when you're done with it!

dansimau