2

I have a PHP script that run on console.

while(1) {
 doStuff();
 sleep(2);
}

I need to accept input from the console. I don't want loop stop each time and wait for me to input some text.

What i want is while loop continue as normal, if i type something in console, php script able to read that text and update some variable.

Can this be done ?

Yujin Boby
  • 293
  • 2
  • 10
  • 1
    Possible duplicate of [Interactive shell using PHP](http://stackoverflow.com/questions/5794030/interactive-shell-using-php) – Jay Blanchard Jan 15 '16 at 20:36

1 Answers1

4

You can do this with non-blocking I/O. You'll need the stream_set_blocking method and stream_select:

stream_set_blocking(STDIN, FALSE);

while (1) {
    doStuff();

    $readStreams = [STDIN];
    $timeout = 2;

    // stream_select will block for $timeout seconds OR until STDIN
    // contains some data to read.
    $numberOfStreamsWithData = stream_select(
        $readStreams,
        $writeStreams = [],
        $except = [],
        $timeout
    );

    if ($numberOfStreamsWithData > 0) {
        $userInput = fgets(STDIN);

        // process $userInput as you see fit
    } else {
        // no user input; repeat loop as normal
    }
}
helmbert
  • 35,797
  • 13
  • 82
  • 95