php PHP中的键盘输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/941744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keyboard input in PHP
提问by blueintegral
I am trying to control stuff with PHP from keyboard input. The way I am currently detecting keystrokes is with:
我正在尝试通过键盘输入来控制 PHP 的内容。我目前检测击键的方式是:
function read() {
$fp1=fopen("/dev/stdin", "r");
$input=fgets($fp1, 255);
fclose($fp1);
return $input;
}
print("What is your first name? ");
$first_name = read();
The problem is that it is not reading the keystrokes 'live'. I don't know if this is possible using this method, and I would imagine that this isn't the most effective way to do it either. My question is 1) if this is a good way to do it, then how can I get it to work so that as you type on the page, it will capture the keystrokes, and 2) if this is a bad way of doing it, how can I implement it better (maybe using ajax or something)?
问题在于它不是“实时”读取击键。我不知道使用这种方法是否可行,我认为这也不是最有效的方法。我的问题是 1) 如果这是一个很好的方法,那么我怎样才能让它工作,以便当您在页面上输入时,它会捕获击键,以及 2) 如果这是一种不好的方法,我怎样才能更好地实现它(也许使用 ajax 或其他东西)?
edit: I am using PHP as a webpage, not command line.
编辑:我使用 PHP 作为网页,而不是命令行。
回答by Andrew Flanagan
I'm assuming that you're using PHP as a web-scripting language (not from the command line)...
我假设您使用 PHP 作为网络脚本语言(而不是从命令行)...
From what I've seen, you'll want to use Javascript on the client side to read key inputs. Once the server delivers the page to the client, there's no PHP interaction. So using AJAX to read client key inputs and make calls back to the server is the way to go.
从我所见,您会希望在客户端使用 Javascript 来读取关键输入。一旦服务器将页面交付给客户端,就没有 PHP 交互。因此,使用 AJAX 读取客户端键输入并调用回服务器是可行的方法。
There's some more info on Javascript and detecting key presses hereand some info on how to use AJAX here.
有JavaScript的一些详细信息和检测按键位置以及如何使用AJAX一些信息在这里。
A neat option for jQuery is to use something like delayedObserver
jQuery 的一个不错的选择是使用诸如delayObserver 之类的东西
回答by rodion
If you are writing a CLI application (as opposed to a web application), you can use ncurses' getch()function to get a single key stroke. Good luck!
如果您正在编写 CLI 应用程序(而不是 Web 应用程序),您可以使用ncurses 的 getch()函数来获取单个按键。祝你好运!
If you're not writing a CLI application, I would suggest following Andrew's answer.
如果您不是在编写 CLI 应用程序,我建议您遵循 Andrew 的回答。

