When using command-line PHP capturing input is a bit different than when building a web application. Instead of building a form and interrogating some variables, you have to actually prompt the user for the input and then analyze it to determine if what the user input was what you were looking for (in the case of yes/no prompts for example).
The first example is how to read a single line of input from a user:
$input = trim(fgets(STDIN));
PHPAdditionally, you can use fscanf
to format the input from the user, in this case, reading in a number:
trim(fscanf(STDIN, "%d\n", $numeric_input));
PHPBut what about a scenario where you want to continue to prompt a user until they enter a specific string? You could very well pull directly from STDIN
every time, but you could also open an I/O stream that you can interact with inside of a loop:
$stdin = fopen('php://stdin', 'r');
$yes = false;
while (!$yes) {
echo 'y or n? ';
$input = trim(fgets($stdin));
if ($input == 'y') {
exit('YES!!');
}
}
PHPSo why do we trim()
the input? Because the user has to hit enter before the input is sent in, so we’re just trimming that off. If you weren’t to trim it, our conditional would have been more like if ($input == "yn") { ... }
. That’s obviously your choice, but I find trimming the value to take out the guess work!