flori
flori

Reputation: 15837

Run an interactive shell command from PHP in CLI mode

I have a PHP CLI script and want to execute an interactive bash command (e.g. less huge-file.txt) from that script and get the same view (with less e.g. the navigation controls) as if I had started it directly from the terminal.

The normal system() call is not enough because they don't pause and just return all the output at once (in the case of e.g. less).

Sense is that I have a CLI script that organises several tasks. Some of them use complex bash commands and I just want to invoke the bash scripts from PHP but get the original terminal behaviour.

Upvotes: 1

Views: 1394

Answers (2)

flori
flori

Reputation: 15837

proc_open( 'less huge-file.txt', array( STDIN, STDOUT, STDERR), $pipes);

This calls the command and passes all controls etc. through, so that there is no distinction to a normal less huge-file.txt.

Still a bit clunky but a lot shorter compared to other examples I could find.

Upvotes: 2

MerlinTheMagic
MerlinTheMagic

Reputation: 605

Yes it is possible. I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS

I doubt you are really looking to script using less (that will get ugly, head / tail / sed /awk are your friends in text manipulation), but getting a real shell behavior is very possible.

After downloading you would simply use the following code:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);

//open file in less. $return1 will contain the view and the first part of the file you opened. The second argument is needed to delimit the return since less will not end in a shell prompt.
$return1  = $shell->exeCmd('less /path/to/huge-file.txt', 'huge-file.txt');

//quit less, you must do this or the shell will hang on the less prompt and will have to be forcefully terminated.
$return2  = $shell->exeCmd('q');

Upvotes: 0

Related Questions