Skip to content
Advertisement

PHP: Adding Arrow Key Support to STDIN/Single Character Processing

In PHP, I can read in input from a command line program with the following code

$stream = STDIN;
$test = fgets($stream);
echo $test;

This works well for simple input. However, if I try to use something like an back arrow key, my shell looks like the following

This is a test^[[D^[[D^[[D    

i.e., the arrow key escape sequence of ^[[D is sent to the shell. PHP itself will interpret the arrow keys — i.e. inputing this

This is a test^[[D^[[D^[[D^[[Dsecond test     

will output this

This is a second test

However, I’d like the shell to “correctly” (i.e. do what I think they should do, not literally what I sent) interpret the arrow keys so the insertion point moves while typing.

Is this possible in PHP? With an extension? Without an extension? I’ve tried variations of fgets($stream, 1) but it seems like PHP just hangs until the user inputs an enter key.

Advertisement

Answer

No way with pure PHP: http://php.net/fgetc (see the comments)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement