Search code examples
phpstdin

PHP: How to track the timeout of the absence of input data?


There is code which recieves input lines from STDIN:

#!/usr/bin/php
<?php
while (false !== ($line = fgets(STDIN))) {
      if (preg_match('/start/',$line)) {
         echo $line , "\n";
      }
}
?>

My question is: how to track the timeout of the absence of input data for 1 minute and inform if in case?


Solution

  • I resolved my issue using answer of hek2mgl from here [PHP CLI - Ask for User Input or Perform Action after a Period of Time

    This is my code :

    #!/usr/bin/php
    <?php
    echo "input something ... (5 sec)\n";
    $stdin = fopen('php://stdin', 'r');
    
    while(true) {
    $read = array($stdin);
    $write = $except = array();
    $timeout = 5;
    
        if(stream_select($read, $write, $except, $timeout)) {
              $line = fgets($stdin);
              if (preg_match('/start/',$line)) {
                    echo $line , "\n";
              }
        } else {
           echo "you typed nothing\n";
        }
    }
    ?>