问题
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