views:

2350

answers:

3

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.

+4  A: 

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

Andrew Flanagan
He's not using a web interface, he's using PHP's command line interface. No JavaScript (or even HTML) there.
ceejayoz
He talks about the "page" and AJAX so I assume he's dealing with a web page.
Andrew Flanagan
Do you happen to know of a place where I can get some sample javascript to do this? I'm still learning web scripting.
aloishis89
Added a link to the answer... You'll want to combine detecting key press events with an AJAX call.
Andrew Flanagan
An ajax call for every keypress is probably undesirable -- that'd result in a lot of HTTP requests, and UI latency. Instead, you're really going to want to interpret a set of keypresses in javascript, and make a single call when necessary.
Frank Farmer
A: 

Try readline:

http://us3.php.net/manual/en/function.readline.php

thedz
Readline will only return a whole new line, while the OP is interested in single key strokes.
rodion
Also, the readline library is not available on many PHP default installations.
chiborg
+1  A: 

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!

If you're not writing a CLI application, I would suggest following Andrew's answer.

rodion