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 function below is a simplified version of @seb's answer that can be used to capture a single character. It does not require stream_select
, and uses readline_callback_handler_install
's inherent blocking rather than creating a while loop. It also removes the handler to allow further input as normal (such as readline).
function readchar($prompt)
{
readline_callback_handler_install($prompt, function() {});
$char = stream_get_contents(STDIN, 1);
readline_callback_handler_remove();
return $char;
}
// example:
if (!in_array(
readchar('Continue? [Y/n] '), ["\n", 'y', 'Y']
// enter/return key ("\n") for default 'Y'
)) die("Good Bye\n");
$name = readline("Name: ");
echo "Hello {$name}.\n";