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?
The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/. php_history file. The CLI SAPI provides the php.
PHP has a REPL; if you haven't used it yet, run php –a in a terminal. This will take you to the interactive PHP prompt at which you can enter your code. All programming language REPLs work essentially the same way.
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.
Since this question has been asked and answered, a better solution has been added to PHP. In all recent PHP versions you can easily get user input as so:
$input = fgets(STDIN);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With