Skip to content

Instantly share code, notes, and snippets.

@zither
Last active August 29, 2015 14:17
Show Gist options
  • Save zither/d96ee697fb718994ae43 to your computer and use it in GitHub Desktop.
Save zither/d96ee697fb718994ae43 to your computer and use it in GitHub Desktop.
Read a single character of input from the TTY without waiting for the enter in PHP CLI
#!/usr/bin/env php
<?php
// 保存当前 tty 设置
$term = shell_exec("stty -g");
// 关闭 tty 规范输入模式
// link http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92
system("stty -icanon");
while ($c = fread(STDIN, 1)) {
printf("%c\n", $c);
}
// 重置 tty 设置
system(sprintf("stty %s", $term));
#!/usr/bin/env php
<?php
readline_callback_handler_install('', function () {});
while (true) {
$read = array(STDIN);
$write = $except = null;
$number = stream_select($read, $write, $except, 0, 100000);
if ($number && in_array(STDIN, $read)) {
$char = stream_get_contents(STDIN, 1);
echo "Char read: $char\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment