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 ?

1

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.