Search code examples
stdinphp

How can I clear the php STDIN before a new input?


I have a nooby question about php-cli.

I'm using this :

define("STDIN", fopen('php://stdin','r'));
$input = "";
while($input == "") {
   echo "Please enter : ";
   $input = fread(STDIN, 80);
}

Problem is :

If I enter more than 80 characters, say 100, the 20 extras characters are added to the next one.

How can i "clear" the STDIN before each input ?


Solution

  • Set length argument of fread() to higher value (i.e. 1024, 2048, 10000) - it determines max lenght of data read by fread(). If you need just up to 80 characters, then check that after the read and shorten using substr() when needed. You do not need to open the input stream if you use STDIN (docs) which is recommended due to bugs in handling of php://stdin up to PHP 5.2.1 (docs).

    $input = "";
    while($input == "") {
       echo "Please enter : ";
       $input = fread(STDIN, 10000);
    }
    

    Also bear in mind STDIN, STDOUT, STDERR are already defined system constants. You should not use these names for your own constants.