Viewed   287 times

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.

 Answers

2

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.

Tuesday, August 30, 2022
 
sejong
 
2

Problem solved with the following command:

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("C:wampbinphpphpVERSIONNUMBERphp-win.exe -f C:/wamp/www/path/to/backgroundProcess.php", 0, false);
Friday, December 9, 2022
3

Try using the direct path of the application (/usr/bin/unrar of whatever), it sounds like php can't find the application.

Thursday, September 1, 2022
5

Can you change the function to not take any arguments? The variables is then looked up from the locals/globals where you can supply into exec:

>>> def spam():
...   print "spam and", eggs
... 
>>> exec(spam.__code__, {'eggs':'pasta'})
spam and pasta

(Why not just send the whole function as a string? Pickle "def spam(eggs): print 'spam and', eggs", and exec the string (after verification) on the other side.)

Sunday, December 18, 2022
 
4

Either you change to that directory within the exec command (exec("cd Scripts && ./script.sh")) or you change the working directory of the PHP process using chdir().

Wednesday, August 24, 2022
 
gpapaz
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :