Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

exec

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.

like image 817
Gmap4 guy Avatar asked Dec 29 '10 01:12

Gmap4 guy


1 Answers

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.

like image 176
dansimau Avatar answered Nov 15 '22 11:11

dansimau