PHP CLI-一段时间后要求用户输入或执行操作 [英] PHP CLI - Ask for User Input or Perform Action after a Period of Time
问题描述
我正在尝试创建一个PHP脚本,要求用户选择一个选项:基本上像这样:
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.
但我想对此进行扩展,以便如果用户在5秒内未键入某些内容,则默认操作将自动运行而无需任何操作来自用户的进一步操作。
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.
使用PHP完全可行吗...?不幸的是,我是这个主题的初学者。
Is this at all possible with PHP...? unfortunately I am a beginner on this subject.
任何指导都将不胜感激。
Any guidance is greatly appreciated.
谢谢,
Hernando
推荐答案
您可以使用 stream_select()
为此。这里有一个例子。
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";
}
这篇关于PHP CLI-一段时间后要求用户输入或执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!