Command line: Request input?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
TS_Death_Angel
Forum Commoner
Posts: 31
Joined: Sat Dec 31, 2005 8:49 am

Command line: Request input?

Post by TS_Death_Angel »

Is there a way for a PHP script running from the command line to request user input via keyboard?
Ex. Please enter your age: [cursor]

Thanks.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Several ways, enumerated in the PHP manual section on CLI scripting.

Personally, I prefer this on Windows systems:

Code: Select all

// set up streams
$GLOBALS['stdin']  = fopen('php://stdin',  'r');

// Sets up a prompt for command line scripts
function cli_prompt($length = 255) {
    $line = fgets($GLOBALS['stdin'],$length);
    return trim($line);
}

// ...

echo "Please enter your age: ";
$age = cli_prompt();
I believe there is a constant for stdin when you're on Unix.
TS_Death_Angel
Forum Commoner
Posts: 31
Joined: Sat Dec 31, 2005 8:49 am

Post by TS_Death_Angel »

Cheers :D You can't imagine how long I've been looking for the solution to this... :P Thanks again.
Post Reply