5

我正在尝试创建一个 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 ......?不幸的是,我是这个主题的初学者。

非常感谢任何指导。

谢谢,

埃尔南多

4

2 回答 2

5

你可以使用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";
}
于 2013-05-09T16:17:27.453 回答
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 再次感谢!

于 2013-05-09T17:16:10.710 回答