Search code examples
phpinputconsolebufferstdin

Read input value from console/cli at the moment of the question


I've a problem reading input commands from a console application made in php.

PROBLEM

If a user using console for mistake press two or more times ENTER or some chars, while process is loading, the command is read before ask the question then skipping the next one.

I tried these methods for catch input value but I find everytime the same issue:

fgets(STDIN);
readline("Question: ");
stream_get_line(STDIN, 1024, "\n");

Code Example:

<?php
for($i = 0; $i < 15; $i++){
    $read = readline("Question $i: "); // Look at the number
    echo "Your answer is: " . $read . PHP_EOL;
    sleep(2); // Now on execution try press ENTER one ore more times
}

ATTEMPTS

I tried this but this method doesn't work on buffers (I tried anyways for be sure):

$handle = fopen('php://stdin', 'r+');
ftruncate($handle, 0);
rewind($handle);
fclose($handle);
$read = readline("Question: ");

QUESTION

How i can read and wait for input at the moment of question display discarding the previous input?


Solution

  • SOLUTION

    I've resolved as follow:

    <?php
    for($i = 1; $i < 10; $i++){
        /* BEGIN: SOLUTION */
        // Read/Clean buffer until isn't empty
        while(stream_select($read = [STDIN], $write = [], $except = [], 0)){
          fgets(STDIN);
        }
        /* END: SOLUTION */
        $read = readline("Question $i: "); // Look at the number
        echo "Your answer is: " . $read . PHP_EOL;
        sleep(2); // Now on execution try press ENTER one ore more times
    }