PHP CLI-请求用户输入或在一段时间后执行操作

PHP CLI-请求用户输入或在一段时间后执行操作,php,command-line-interface,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 p

我正在尝试创建一个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中是可能的吗。。。?不幸的是,我是这门学科的初学者

非常感谢您的指导

谢谢

赫尔南多

你可以用它。这里有一个例子

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

再次感谢您

您可能需要使用,因为从头开始重建此功能会很困难。如果您使用流函数从stdin读取,那么您应该能够使用查看是否解决了您的问题谢谢大家。。。瓦利德,对我来说,当然是当有人在交通中打断我时我所做的…;)对我来说这是一个学期的大学课程。。。阿尼格尔,我正试着消化你推荐的东西。戈登,我以前看过这篇文章,但它并没有真正的帮助…hek2mgl-这就像一个符咒。。。非常感谢。我真的不明白这一切是怎么回事,但我可以把它直接放到我的脚本中。再次感谢你@Hernandito
stream_select()
如果在
$timeout
秒内未进行任何输入,则返回
false
。。请注意我的控制台软件包。这对你应该有帮助。。我刚刚添加了一个功能请求来实现超时。即将实施:)。。