2013-05-09 45 views
4

我想创建一个PHP脚本,我在那里要求用户选择一个选项的时期后执行操作:基本上是这样的:PHP CLI - 询问用户输入或时间

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 ...?不幸的是,我是这个主题的初学者。

任何指导非常感谢。

感谢,

赫尔南

+0

您可能想要使用[PHP的ncurses](http://php.net/manual/en/book.ncurses.php),因为从零开始重建此功能将很困难。 – 2013-05-09 16:09:24

+0

如果你使用流函数从stdin读取,那么你应该可以使用http://www.php.net/manual/en/function.stream-set-timeout.php – Anigel 2013-05-09 16:10:56

+0

看看http:// stackoverflow。 com/questions/11025223/php-cli-get-user-input-while-still-doing-things-in-background解决你的问题 – Gordon 2013-05-09 16:13:32

回答

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"; 
} 
+0

hek2mgl - 这个作品像一个魅力...谢谢!我真的不明白这是什么,但我可以把它放到我的脚本中。再次感谢你!! – Hernandito 2013-05-09 16:27:45

+0

@Hernandito'stream_select()'如果'$ timeout' secs中没有输入完成,则返回'false'。请注意我在[github](https://github.com/metashock/Jm_Console/)上的控制台包。它应该对你有所帮助..我刚刚添加了一个功能请求来实现超时。即将实施:) .. – hek2mgl 2013-05-09 16:30:27

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许多再次感谢!