I want to read a single character at-a-time from the command line in PHP, however it seems as though there is some kind of input buffering from somewhere preventing this.
The solution for me was to set -icanon mode on the TTY (using stty). Eg.:
stty -icanon
So, the the code that now works is:
#!/usr/bin/php
Output:
input# fRead from STDIN: f
input# oRead from STDIN: o
input# oRead from STDIN: o
input#
Read from STDIN:
input#
Props to the answer given here:
Is there a way to wait for and get a key press from a (remote) terminal session?
For more information, see:
http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92
Don't forget to restore the TTY when you're done with it...
Restoring the tty configuration
Resetting the terminal back to the way it was can be done by saving the tty state before you make changes to it. You can then restore to that state when you're done.
For example:
This is the only way to preserve the tty and put it back how the user had it before you began.
Note that if you're not worried about preserving the original state, you can reset it back to a default "sane" configuration simply by doing: