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
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With