Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect/read key pressed, cross-platform PHP CLI

I'm attempting to write a cross-platform PHP utility for personal use, not to reinvent anything. The code will run within more or less

while (true) {
    $key = null;
    $key = check_key_pressed();
    if ($key) do_relevant_magic($key);
    usleep(250000);
}

I need something for check_key_pressed() that will return a value of a pressed key, not waiting for EOF/EOL, not asking for input explicitly until any key is actually pressed.

This has to work on *nix and windows so ncurses is not an option. I also do not want exec calls to external vbs or bash scripts, it has to be done purely in PHP, hope I'm not wishing for too much.

EDIT: Of course I checked other SO solutions and none of them seems to be truly cross-platform. Ncrurses and readline are not available on windows and this has to intercept a keydown or keypress or input ready on both linux and windows.

like image 885
DeDee Avatar asked Jan 24 '15 18:01

DeDee


1 Answers

Unfortunately, this is not possible (still today) without a similar platform-specific extension for Windows like the ones for *n*x (readline, ncurses).

Worse yet, even if you give up the cross-platform requirement, I doubt that there's any such (reasonably well-known) extension for that on Windows. (People tend to recommend writing the bindings for things like pdcurses (which is at least itself cross-platform) yourself, since apparently no-one has quite done and published one yet.)

Things are slowly progressing though, and at least the readline extension is now available for Windows (since 7.1), but it happens to be just short of the unbuffered char read functionality...

like image 62
Sz. Avatar answered Oct 05 '22 06:10

Sz.