PHP stdin Command Line Input From User


In C++ it is called cin, and in perl it is $variable = <STDIN> however what is the equivalent of cin and STDIN for PHP?

In PHP is is similar to perl in that we use php’s I/O stream called stdin. The syntax looks something like this:


Reading User Input From Command Line

To read a user’s input from the command line we use stdin which as I mentioned before, is an I/O stream. Since stdin is an input stream, it can only be opened as read-only. There are two other I/O streams which are stdout and stderr and as they are output stream, they can only be opened in write mode. Opening stdin and reading from it won’t be that difficult and hopefully the example below will show how useful and easy it can be to capture a users input from the command line or other information from stdin and display it back to the user.

PHP stdin Command Line Input From User

The below script will capture a user’s name and then display it to the user.


// show them a message to enter their name
echo "Tell us your name: " . PHP_EOL;

// the script will wait here until the user has entered something and hit ENTER
$name = read_stdin();

// This will display the thank you message including their name they entered.
echo "Thank you $name. Welcome to my site" . PHP_EOL;

// our function to read from the command line
function read_stdin()
	$fr=fopen("php://stdin","r");	// open our file pointer to read from stdin
	$input = fgets($fr,128);	// read a maximum of 128 characters
	$input = rtrim($input);		// trim any trailing spaces.
	fclose ($fr);			// close the file handle
	return $input;			// return the text entered


Final Note

Reading from the command line can be useful for creating php scripts that run from the command line. It can be used to capture the user’s decisions such as specifying the install location or setting up config preferences for a new website.