0

I am trying to achieve a PHP method that I can use to call a shell script or program. That in itself is easy with backticks but then I only get the output when the script/program is finished which is not what I needed.

So I switched to using popen(), so I print the output as it comes in. That works fine now, but I'm running into the next issue for which I couldn't find a working solution: handle prompts from the called script / program. The very nature of my project is so that I can not know upfront whether a script needs user input and thus can not answer prompts automatically. For example a script like apt-get update ; apt-get upgrade might trigger user prompts I am not aware of nor want to answer automatically for the user.

Currently I am using this piece that I found on StackOverflow:

        static public function command($cmd) 
        {
            $cwd = getcwd();  
            $proc = proc_open($cmd, [['pipe','r'],['pipe','w'],['pipe','w']], $pipes, $cwd);

            while(($line = fgets($pipes[1])) !== false) 
            {
                fwrite(STDOUT,$line);
            }

            while(($line = fgets($pipes[2])) !== false) 
            {
                fwrite(STDERR,$line);
            }

            fclose($pipes[0]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            return proc_close($proc);
        }

It works fine for the output, but as soon as the script prompts the user (e.g. with read -p "What's your poison?") I get no output nor can I enter anything. At first I thought it might have to do with the STDIN pipe not being processed any further but I couldn't figure out how to set it up properly.

Can someone guide me in the right direction as to how the implementation would have to look like to support user prompts rather than automatically answering them?

Tox
  • 373
  • 4
  • 13
  • The output of `apt-get` is probably buffered when it's writing to a pipe. – Barmar Sep 03 '19 at 06:37
  • I get the same issue with a simple script like `read -p "What's your poison?" answer`, in fact with any script that makes use of `read`. – Tox Sep 03 '19 at 07:57

1 Answers1

0

Turns out that there is a much simpler solution: just use the passthru() function, it handles user prompts correctly and outputs in real time.

Tox
  • 373
  • 4
  • 13