I want to write a PHP script that I can use from the command line. I want it to prompt and accept input for a few items, and then spit out some results. I want to do this in
I'm not sure how complex your input might be, but readline is an excellent way to handle it for interactive CLI programs.
You get the same creature comforts out of it that you would expect from your shell, such as command history.
Using it is as simple as:
$command = readline("Enter Command: ");
/* Then add the input to the command history */
readline_add_history($command);
If available, it really does make it simple.
Here a typical do-case-while for console implementation:
do {
$cmd = trim(strtolower( readline("\n> Command: ") ));
readline_add_history($cmd);
switch ($cmd) {
case 'hello': print "\n -- HELLO!\n"; break;
case 'bye': break;
default: print "\n -- You say '$cmd'... say 'bye' or 'hello'.\n";
}
} while ($cmd!='bye');
where user can use arrows (up and down) to access the history.
My five cents:
Using STDOUT
and STDIN
:
fwrite(STDOUT, "Please enter your Message (enter 'quit' to leave):\n");
do{
do{
$message = trim(fgets(STDIN));
} while($message == '');
if(strcasecmp($message, 'quit') != 0){
fwrite(STDOUT, "Your message: ".$message."\n");
}
}while(strcasecmp($message,'quit') != 0);
// Exit correctly
exit(0);
Basically you read from standard input. See Input/output streams.