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