PHP Exec command - How to pass input to a series of questions
I have a program on my linux server that asks the same series of questions each time it executes and then provides several lines of output. My goal is to automate the input and output with a php script.
The program is not designed to accept input on the command line. Instead, the program asks question 1 and waits for an answer from the keyboard, then the program asks question 2 and waits for an answer from the keyboard, etc.
I know how to capture the output in an array by writing: $out = array(); exec("my/path/program",$out);
But how do I handle the input? Assume the program asks 3 questions and valid answers are: left 120 n What is the easiest way using php to pass that input to the开发者_JS百科 program? Can I do it somehow on the exec line?
I’m not a php noob but simply have never needed to do this before. Alas, my googling is going in circles.
First up, just to let you know that you're trying to reinvent the wheel. What you're really looking for is expect(1), which is a command-line utility intended to do exactly what you want without involving PHP.
However, if you really want to write your own PHP code you need to use proc_open
. Here are some good code examples on reading from STDOUT and writing to STDIN of the child process using proc_open
:
- http://www.php.net/manual/en/function.proc-open.php#79665
- How to pass variables as stdin into command line from PHP
- http://camposer-techie.blogspot.com/2010/08/ejecutando-comandos-sobre-un-programa.html (this one is in Spanish, sorry, but the code is good)
Finally, there is also an Expect PECL module for PHP.
Hope this helps.
Just add the arguments to the exec line.
exec("/path/to/programname $arg1 $arg2 $arg3");
... but don't forget to apply escapeshellarg()
on every argument! Otherwise, you're vulnerable to injected malicious code.
$out = array();
//add elements/parameters/input to array
string $execpath = "my/path/program ";
foreach($out as $parameter) {
$execpath += $parameter;
//$execpath += "-"+$execpath; use this if you need to add a '-' in front of your parameters.
}
exec($execpath);
精彩评论