Last active
November 14, 2024 03:57
-
-
Save terremoth/4d01668e9f59849d863d37e61d2bc062 to your computer and use it in GitHub Desktop.
How to handle keypress non blocking real time get pressed keys on PHP (Linux only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$stdin = fopen('php://stdin', 'r'); | |
system('stty cbreak -echo'); | |
stream_set_blocking($stdin, false); | |
while (1) { | |
if ($keypress = fgets($stdin)) { | |
echo 'Key pressed: ' . $keypress . PHP_EOL; | |
} | |
// you can do other stuff here since fgets and the stream won't block | |
// allowing to do simple command line games or interactive terminal tools like menus | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A more object oriented approach. I will make a composer installable lib with this and a proper doc, then I will come back here and post the link. The code below I haven't tested yet.