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

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.

5 thoughts on “PHP: Read from Keyboard – Get User Input from Keyboard Console by Typing”

  1. Pingback: WordPress: 503 Service Temporarily Unavailable when Posting New Posts or Modifying Existing Posts

  2. 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.

  3. @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?

Comments are closed.

Scroll to Top