问题
Hi I am using PHP in CLI mode (Command Line Interface)
I would like to get the key the user types and immediately have it submitted to the program without the user having to press the return key(Enter Key) So for example's sake I'ld like it to print the letter the user types immediately. So if the user types an "a" it immediately shows an "a" in the command prompt. How would I do this?
do {
$selection = fgetc(STDIN);
fwrite(STOUT, "$selection");
} while ( trim($selection) == '' );
回答1:
There are few ways to disable input buffering:
http://www.mail-archive.com/php-general@lists.php.net/msg151195.html seems to work:
exec("stty -icanon min 0 time 0");
Some other suggestions are here: http://bugs.php.net/bug.php?id=34972 but stream_set_blocking(STDIN, false);
for example has no effect
回答2:
Either disable buffering on stdin or use ncurses instead.
来源:https://stackoverflow.com/questions/5254415/php-get-user-input-without-user-having-to-press-return-key