PHP loop listen for user input

旧巷老猫 提交于 2019-12-11 11:56:03

问题


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:


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
    }
}


来源:https://stackoverflow.com/questions/34819448/php-loop-listen-for-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!