PHP CLI - user request to enter or perform actions after a certain period of time

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 well, as you can perform certain actions based on user input.

But I would like to expand this so that if the user does not type something within 5 seconds, the default action will be launched automatically without any further user actions.

Is this even possible with PHP ...? Sorry, I'm starting this thread.

Any guidance is appreciated.

Thanks,

Hernando

+4
source share
2 answers

You can use stream_select() . Here is 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"; } 
+3
source

For the hek2mgl code to match my example above, the code should look like this:

 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 thanks again!

0
source

Source: https://habr.com/ru/post/1479949/


All Articles