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 . "
input# ";
}
?>
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…