2013-05-09 43 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許多再次感謝!