Search code examples
phpconsolestdinflushcommand-line-interface

How do I flush STDIN in a PHP console application?


I have a simple command line utility built with PHP and it works great. Unfortunately, we now have some lesser than savvy users pounding away at the keyboard while it's processing data.

Is there a way to flush STDIN so it only starts buffering data from when I used fgetc?

I've tried opening my own STDIN pipe and even flushing the buffer by looping through what's in there which kind of works but doesn't handle multiple CRs.

Rewind and fseek don't seem to do anything with STDIN in PHP.

Seems like it would be a common issue but not much out there.

PHP version 5.3.3

(I don't want to use ncurses if I don't have to)

Any fgets or fgetc will exhibit my problem. For example, if you have a prompt indicating something is "processing" and then start typing away the input is buffered in STDIN so when you actually prompt the user later for something what they type is added to the buffer. So if they typed "abc" while "processing" and then you prompt for something their input is "abc" plus whatever they typed at the prompt by the time you get to fgets or fgetc. So if someone keeps hitting ENTER and you're using fgets (or fgetc wiating for a "\n") then you get premature code continuation.

For example:

echo "Processing";
sleep(10); // HIT ENTER A FEW TIMES HERE
echo "Input Something: ";
// REALLY NEED TO FLUSH STDIN HERE SOMEHOW
fgets(STDIN);

Solution

  • Seems that PHP "readline" is a good way to handle this and I'm going with it.

    Thanks, all!