PHP CLI: How to read a single character of input from the TTY (without waiting for the enter key)?

前端 未结 4 1492
醉梦人生
醉梦人生 2020-11-29 02:53

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.

4条回答
  •  情深已故
    2020-11-29 03:35

    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";
    

提交回复
热议问题