1

I have a terminal-based php program that basically just runs in a big for loop, does a bunch of stuff and then quits. I would like to be able to interrupt the loop, either pausing or quitting the app. Currently I have to hit ^C to quit the app (or kill it from another terminal screen). Any ideas how I might implement this?

Running program... 
[Press Q to quit and <spacebar> to pause at any time]
text
text
text
...
more text scrolling by

I get how to quit and how to pause, that's easy enough, but I'm not sure how to monitor for input while doing tons of other functions.

Thanks much!

justin
  • 164
  • 1
  • 10
  • 1
    [This may](https://stackoverflow.com/questions/8308997/stop-executing-php-for-or-while-loop-in-command-line-with-key-press) help mate... I believe he was perhaps attempting something similar. – Sam Aug 12 '17 at 03:56
  • Check https://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f – Fawzan Aug 12 '17 at 03:59

1 Answers1

2

Found the answer here: Reading line by line from STDIN without blocking

Thanks to the above commenters who gave me some search parameters to get to the right answer ultimately.

The solution is in stream_set_blocking as illustrated below:

<?php
  $stdin = fopen('php://stdin', 'r');
  stream_set_blocking ( $stdin , 0 );

  for( $x=0; $x <=10; $x++) {
  echo "$x\n";

  $line = fgets($stdin);  //Doesn't wait for input because blocking is turned off!
  if (! empty($line)) {
        die();
  }
}
?>
justin
  • 164
  • 1
  • 10