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.

Subscribe to Kavoir: blog feed

You should also read:

mairo June 18, 2009 at 4:52 pm

When you publish a script, please be carefull to type in correct var names and make a syntax check.
Who will use this script maybe is not an expert programmer and so “maybe” he cannot correct your errors.

Yang Yang June 19, 2009 at 8:39 am

@mairo,
Is that the f open function name incorrect? I tried to publish the post by ‘fopen’ but it’s always 503 service temporarily unavailable error from wordpress. I dont’ know why. But once I change ‘fopen’ to ‘f open’, it’s successfully published.

Maybe it’s some wordpress post content filtering bug?

Jonathon Hill September 4, 2009 at 11:54 pm

If you only need one line of input, this will do it for you:

$line = trim(fgets(STDIN));

Yang Yang February 26, 2010 at 5:26 pm

Nice catch!

Comments on this entry are closed.

{ 1 trackback }

Previous post:

Next post: