PHP Command-Line PHP
Reading from the Keyboard
Problem
You need to read in some typed user input.
Solution
Read from the special filehandle STDIN:
print "Type your message. Type '.' on a line by itself when you're done.\n";
$last_line = false; $message = '';
while (! $last_line) {
$next_line = fgets(STDIN,1024);
if (".\n" == $next_line) {
$last_line = true;
} else {
$message .= $next_line;
}
}
print "\nYour message is:\n$message\n";
If the Readline extension is installed, use readline():
$last_line = false; $message = '';
while (! $last_line) {
$next_line = readline();
if ('.' == $next_line) {
$last_line = true;
} else {
$message .= $next_line."\n";
}
}
print "\nYour message is:\n$message\n";
If the ncurses extension is installed, use ncurses_getch():
$line = '';
ncurses_init();
ncurses_addstr("Type a message, ending with !\n");
/* Display the keystrokes as they are typed */
ncurses_echo();
while (($c = ncurses_getch()) != ord("!")) {
$line .= chr($c);
}
ncurses_end();
print "You typed: [$line]\n";
Discussion
With the special filehandle STDIN, you can use all the standard file-reading functions to process input (fread(), fgets(), etc.). The Solution uses fgets(), which returns input a line at a time. If you use fread(), the input still needs to be newline terminated to make fread() return. For example, if you run:
$msg = fread(STDIN,4);
print "[$msg]";
and type in tomato and then a newline, the output is [toma]. The fread() grabs only four characters from STDIN, as directed, but still needs the newline as a signal to return from waiting for keyboard input.
The Readline extension provides an interface to the GNU Readline library. The readline() function returns a line at a time, without the ending newline. Readline allows Emacs- and vi-style line editing by users. You can also use it to keep a history of previously entered commands:
$command_count = 1;
while (true) {
$line = readline("[$command_count]--> ");
readline_add_history($line);
if (is_readable($line)) {
print "$line is a readable file.\n";
}
$command_count++;
}
This example displays a prompt with an incrementing count before each line. Because each line is added to the Readline history with readline_add_history(), pressing the up and down arrows at a prompt scrolls through the previously entered lines.
The ncurses extension is an interface to the GNU ncurses library, which provides comprehensive control over keyboard events, mouse events, and screen output in text mode. The primary way to read keyboard input with ncurses is the ncurses_getch() function, which returns the ASCII code for the key pressed.
A key difference between ncurses and the other two methods described here is that no newline is required before the keystroke is processed. The ncurses_getch() function returns right away after one keypress. In the example in the Solution, the code loops, repeatedly calling ncurses_getch() (and appending the typed character to $line) until ! is typed.
No comments:
Post a Comment