我试图创建一个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
您可以使用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";
}
要使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再次感谢!