How to Capture User Input from Command-line PHP

Josh Sherman
1 min read
Software Development PHP

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));

Additionally, 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));

But 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')

So 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 sanity check would have been more like if ($input == "y\n") { ... }. That’s obviously your choice, but I find trimming the value to take out the guess work!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles