Search code examples
phpkeyboard-events

Keyboard input in PHP


I am trying to control stuff with PHP from keyboard input. The way I am currently detecting keystrokes is with:

 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)?

edit: I am using PHP as a webpage, not command line.


Solution

  • I'm assuming that you're using PHP as a web-scripting language (not from the command line)...

    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.

    There's some more info on Javascript and detecting key presses here and some info on how to use AJAX here.

    A neat option for jQuery is to use something like delayedObserver