Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CLI - Ask for User Input or Perform Action after a 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 nicely as one 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 run automatically without any further action from the user.

Is this at all possible with PHP...? unfortunately I am a beginner on this subject.

Any guidance is greatly appreciated.

Thanks,

Hernando

like image 301
Hernandito Avatar asked May 09 '13 16:05

Hernandito


1 Answers

You can use stream_select() for that. Here comes 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";
}
like image 109
hek2mgl Avatar answered Sep 24 '22 02:09

hek2mgl