0

My friend uses an application through the terminal in Ubuntu. I'm not sure of the name of it, its some kind of math program. He opens a terminal, types in the command to start the program and then the terminal prompt changes to a prompt for his program and he can enter commands and it will give him back output.

Anyway, he was saying he would like to have an interface to this application on a webpage but he knows very little about web development. So, the way I see it is someone would go to the (PHP based) website, enter some commands in a form and click submit...then the server would start up this terminal program (better yet, have it already running) send the commands to it, get whatever output it gives, and send that back to the user's browser.

So I am wondering can this be done with PHP? Can I interact with some program running in a terminal through PHP?

4
  • 1
    Take a look at exec. Commented May 6, 2012 at 22:30
  • 1
    It can be done. Doing it safely is another matter. Anything that involves taking user input and passing it to an external exec()'d program is HIGHLY dangerous unless you know what you're doing. Commented May 6, 2012 at 22:32
  • 1
    @csss take a look at this php.net/manual/es/function.shell-exec.php but as Marc says be careful Commented May 6, 2012 at 22:34
  • 1
    For interactivity via stdin you need pipes, available with php.net/manual/es/function.proc-open.php Commented May 6, 2012 at 22:37

1 Answer 1

5

The program is probably running in interactive mode when you run it at the prompt. Try running command -h (command being the name of the program) to see if there's a non-interactive mode that just accepts a line of input and outputs a single line in response.

If so, you can get the input with a simple POST form, then use:

echo shell_exec("command -options ".escapeshellarg($_POST['input']));

Where command is again the program name, -options is any options you need to make it run in non-interactive mode, and $_POST['input'] is the form variable.


Alternatively, if the program does not support non-interactive mode, you will need to use proc_open and related functions. Something along these lines:

if( $process = proc_open(
    "command",
    Array(
        Array("pipe","r"),
        Array("pipe","w"),
        Array("file","errors.log")
    ),
    $pipes
)) {
    fwrite($pipes[0],$_POST['input']);
    fclose($pipes[0]);
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    proc_close($process);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.