I want to know how I can interact with a program that I run in a command line PHP script. The scenario is:
- Start executing a program.
- Read the output until a question is being asked (by reading STDOUT I guess).
- Type the answer and press Enter (by writing to STDIN I guess). The user is not to input this, the script already knows what to answer by reading and interpreting the output from step 2.
- Again read the output until a new question is being asked.
- Again type the answer and press Enter. Again, the script knows it all, no user input is to take place.
- This question/answer scenario repeats x number of times until the program is finished.
How can I write a PHP script that does this? I'm thinking that I probably want to use proc_open()
but I can't figure out how. I'm thinking it would be something like this but it doesn't work of course:
$descriptorspec = array(
0 => array('pipe', 'r'), //STDIN
1 => array('pipe', 'w'), //STDOUT
2 => array('pipe', 'r'), //STDERR
);
$process = proc_open('mycommand', $descriptorspec, $pipes, null, null);
if (is_resource($process)) {
// Get output until first question is asked
while ($buffer = fgets($pipes[1])) {
echo $buffer;
}
if (strpos($buffer, 'STEP 1:') !== false) {
fwrite($pipes[0], "My first answer\n"); //enter the answer
} else {
die('Unexpected last line before question');
}
// Get output until second question is asked
while ($buffer = fgets($pipes[1])) {
echo $buffer;
}
if (strpos($buffer, 'STEP 2:') !== false) {
fwrite($pipes[0], "My second answer\n"); //enter the answer
} else {
die('Unexpected last line before question');
}
// ...and so we continue...
} else {
echo 'Not a resource';
}
UPDATE: I figured out that the program outputs the questions to STDERR (because it writes STDOUT to a file).