我正在尝试创建一个PHP脚本,我要求用户选择一个选项:基本上类似于:
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";
}
这可以很好地工作,因为可以根据用户输入执行某些操作。
但我想扩展这一点,以便如果用户在5秒内未输入某些内容,则默认操作将自动运行,而无需用户采取任何进一步操作。
这完全可以用PHP ...?不幸的是,我是这个主题的初学者。
非常感谢任何指导。
谢谢,
Hernando的
答案 0 :(得分:3)
您可以使用stream_select()
。这是一个例子。
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";
}
答案 1 :(得分:0)
为了使hek2mgl代码完全适合我上面的示例,代码需要看起来像这样......:
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再次感谢!!