DeDee
DeDee

Reputation: 2002

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.

Upvotes: 11

Views: 4189

Answers (2)

Zenithies
Zenithies

Reputation: 66

As of 2023, there is still no native solution for Windows. However, it is possible to intercept keys via the PHP COM extension. A full solution for the Windows x64 platform and *nix with readline support is available here:

https://github.com/zenithies/php-toolkit-read-key

You can create your own Windows solution if you like, recipe:

  • create ATL COM DLL with method for intercepting keypress
  • register dll using regsrv32
  • use PHP COM extension and create wrapper for you DLL

Upvotes: 0

Sz.
Sz.

Reputation: 3634

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...

Upvotes: 3

Related Questions