PHP CLI - Ask for User Input or Perform Action after a Period of Time

混江龙づ霸主 提交于 2020-05-13 05:09:26

问题


I am trying to create a PHP script, where I ask the user to select an option: Basically something like:

echo "Type number of your choice below:";

echo "  1. Perform Action 1";
echo "  2. Perform Action 2";
echo "  3. Perform Action 3 (Default)";

$menuchoice = read_stdin();

if ( $menuchoice == 1) {
    echo "You picked 1";
    }
elseif ( $menuchoice == 2) {
    echo "You picked 2";
    }
elseif ( $menuchoice == 3) {
    echo "You picked 3";
    }

This works nicely as one can perform certain actions based on user input.

But I would like to expand this so that if the user does not type something within 5 seconds, the default action will run automatically without any further action from the user.

Is this at all possible with PHP...? unfortunately I am a beginner on this subject.

Any guidance is greatly appreciated.

Thanks,

Hernando


回答1:


You can use stream_select() for that. Here comes an example.

echo "input something ... (5 sec)\n";

// get file descriptor for stdin 
$fd = fopen('php://stdin', 'r');

// prepare arguments for stream_select()
$read = array($fd);
$write = $except = array(); // we don't care about this
$timeout = 5;

// wait for maximal 5 seconds for input
if(stream_select($read, $write, $except, $timeout)) {
    echo "you typed: " . fgets($fd) . PHP_EOL;
} else {
    echo "you typed nothing\n";
}



回答2:


To make hek2mgl code fit exactly to my sample above, the code needs to look like this...:

echo "input something ... (5 sec)\n";

// get file descriptor for stdin
$fd = fopen('php://stdin', 'r');

// prepare arguments for stream_select()
$read = array($fd);
$write = $except = array(); // we don't care about this
$timeout = 5;

// wait for maximal 5 seconds for input
if(stream_select($read, $write, $except, $timeout)) {
//    echo "you typed: " . fgets($fd);
        $menuchoice = fgets($fd);
//      echo "I typed $menuchoice\n";
        if ( $menuchoice == 1){
                echo "I typed 1 \n";
        } elseif ( $menuchoice == 2){
            echo "I typed 2 \n";
        } elseif ( $menuchoice == 3){
            echo "I typed 3 \n";
        } else {
            echo "Type 1, 2 OR 3... exiting! \n";
    }
} else {
    echo "\nYou typed nothing. Running default action. \n";
}

Hek2mgl many thanks again!!



来源:https://stackoverflow.com/questions/16466200/php-cli-ask-for-user-input-or-perform-action-after-a-period-of-time

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