4

This is a little tricky so bear with me:

  • I have a PHP script a.php that is launched from the command line and data is provided to it via STDIN
  • I have another PHP script b.php
  • I want to have a.php launch b.php and capture its output.
  • Also, a.php has to forward the STDIN to b.php

Is there an easy way to do this?

2 Answers 2

3

For just capturing the stdout of another program (php or not), you can use backticks: http://php.net/manual/en/language.operators.execution.php. For example:

$boutput = `php b.php`;

To capture stdin, do this:

$ainput = file_get_contents('php://stdin');

Finally, to pipe the contents of a string to an external program, use proc_open, as suggested by jeremy's answer. Specifically, here's what your a.php should contain:

$ainput = file_get_contents('php://stdin');
$descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
);
$process = proc_open('php b.php', $descriptorspec, $pipes);
fwrite($pipes[0], $ainput);
fclose($pipes[0]);
echo stream_get_contents($pipes[1]); # echo output of "b.php < stdin-from-a.php"
fclose($pipes[1]);
proc_close($process);
Sign up to request clarification or add additional context in comments.

5 Comments

Do you mean you want to allow B.php to accept commands via STDIN when calling from A.php? Would it not be better to just include from that point, and wrap the output around an ob_start and ob_get_flush command?
Uh... I can't pass 'php b.php' to fopen.
Sorry, my first attempt was buggy. I tested what's there now and it seems to work.
It works on Windows.... but now it doesn't work on my linux server. Your answer was the most helpful though. +1
OH NO! proc_open is disabled on my server... oh dear... now what?
1

proc_open() should give you the level of control you need to do this.

1 Comment

This looks promising. I'll give it a shot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.