Just wondering, is it possible to create an interactive shell, using PHP alone. I mean something like you have with databases, python, etc.
If it is, how?
Since PHP has a built-in unix only function readline()
to do exactly that, here leaving the following notes.
We can use and hold the result of readline
into a var.
#!/usr/bin/php
<?php
$user = readline("List dir [l] | Say hello [h] | exit [q]: ");
if ($user === "l"){ system("ls"); }
if ($user === "h"){ echo "Hello!"; }
if ($user === "q"){ exit; }
echo "\nThanks!";
Example output:
l
ls result
h
«hello»
q
exit
ctrl+c
exit.
ctrl+d
with empty input, continue to the next sequence. «Thanks». $user
is defined and empty, no error.
ctrl+d
with some input: No action. Still waiting for input.
ctrl+m
Continue and take the current input in $user
.
ctrl+j
Continue and take the current input in $user
, same behavior as ctrl+m
.
Return
continue to the next sequence «Thanks». $user
can stay empty, no error.
ctrl+z
may be used to cancel a loop and move to the top one. $user
will be unset if the var is not defined in this scope.
Depending input, we can define empty values using!empty
or do more surgical testings (the readline response can be many chars).
$user
can be tested with !isset
if not yet asked.
There is also the built-in readline_add_history()
to store the user input into an object, where values can be retrieved directly by their name (Nice for code clarity):
readline_add_history($user);
print_r(readline_list_history());
print_r(readline_user());
Very useful to build real complex stuffs!
http://php.net/manual/en/function.readline.php
Yes, it's possible. In order to be interactive, the program must be able to wait for and read in user input from stdin. In PHP, you can read from stdin by opening a file descriptor to 'php://stdin'. Taken from an answer to different question, here's an example of an interactive user prompt in PHP (when run from the command line, of course):
echo "Continue? (Y/N) - ";
$stdin = fopen('php://stdin', 'r');
$response = fgetc($stdin);
if ($response != 'Y') {
echo "Aborted.\n";
exit;
}
Of course, to get a full line of input rather than a single character, you'd need fgets() instead of fgetc(). Depending what your program/shell will do, the whole program might be structured as one big continuous loop. Hopefully that gives you an idea how to get started. If you wanted to get really fancy (CLI pseudo-GUI), you could use ncurses.