PHP: Read from Keyboard – Get User Input from Keyboard Console by Typing

by Yang Yang on April 22, 2009

As I said how to parse php program command line arguments in the previous post, reading from user keyboard or console is also a considerable part of making interactive command line programs.

How to let user type in something and make the php script read from the keyboard so that it can identify the user input and use it?

You need a special file: php://stdin which stands for the standard input.

print "Type your message. Type '.' on a line by itself when you're done.\n";

$fh = fopen('php://stdin', 'r');
$last_line = false;
$message = '';
while (!$last_line) {
    $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard
    if (".\n" == $next_line) {
      $last_line = true;
    } else {
      $message .= $next_line;

The user will keep typing with carriage returns until the last line”.\n”, the input ends and $message has all the lines of string entered by the user from keyboard.