PHP Exec command - How to pass input to a series of questions

不问归期 提交于 2019-12-30 09:01:53

问题


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 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.


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4550803/php-exec-command-how-to-pass-input-to-a-series-of-questions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!