PHP Get user input without user having to press return key

亡梦爱人 提交于 2019-12-10 20:55:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!