Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive shell using PHP

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?

like image 594
The Dude With A Moustache Avatar asked Apr 26 '11 17:04

The Dude With A Moustache


People also ask

What is PHP interactive shell?

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.

Does PHP have a REPL?

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.


2 Answers

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.

like image 124
Wiseguy Avatar answered Oct 20 '22 19:10

Wiseguy


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); 
like image 34
dotancohen Avatar answered Oct 20 '22 20:10

dotancohen