Her*_*ito 5 php command-line-interface
我正在尝试创建一个 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";
}
Run Code Online (Sandbox Code Playgroud)
这非常有效,因为人们可以根据用户输入执行某些操作。
但我想对此进行扩展,以便如果用户在 5 秒内没有键入内容,默认操作将自动运行,而无需用户执行任何进一步操作。
这对于 PHP 来说是可能的吗...?不幸的是我是这个主题的初学者。
非常感谢任何指导。
谢谢,
埃尔南多
你可以用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";
}
Run Code Online (Sandbox Code Playgroud)