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.

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

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');