argb
argb

Reputation: 141

how get the output from process opend by popen in php?

file a.php:

<?php
echo "abcdef";
?>

file b.php:

<?php
$h=popen('php a.php',r);
pclose($h);
?>

question:

I can't see the echo result on console; why and how to see it?

I don't want to do it in file b.php like:echo stream_get_contents($h);

Upvotes: 14

Views: 17832

Answers (3)

Behrooz Moghaddam
Behrooz Moghaddam

Reputation: 115

try this:

while (@ ob_end_flush()); // end all output buffers if any
$proc = popen('/path/to/executable 2>&1', 'r');
while (!feof($proc))
{
    echo fread($proc, 4096);
    @ flush();
}

Upvotes: 0

A guest PHP coder
A guest PHP coder

Reputation: 51

You cannot see the echo result on the console because it never went to the console. By opening the process in read-mode, its STDOUT was linked the file handle of the open process. The only way the output would get to the console would be if you read from that file handle, then echoed it.

The flow, in other words, is this.

  • b.php begins running - its STDIN and STDOPUT linked to your console as usual
  • it calls popen in read mode and stores the stream resource in $h
  • this causes a.php to start running, with its STDOUT linked to the file descriptor in $h, and its STDIN not linked to anything
  • this means, as you can see, that a.php has no direct access to the console from which b.php was started
  • a.php writes its output to that stream, and then finishes running
  • b.php never does anything with the stream in $h, it just closes it, so the output of a.php is lost.

Hope that explains what is going on here. If you want to see the output of a.php on the console, then b.php needs to read it from the stream in $h, then echo it, since only b.php has access to the console.

Alternatively, if you use system() instead of popen(), the output will be output on the calling script's console automatically, because using system() hands over the main script's STDIN and STOUT to the program or script that you call.

Upvotes: 5

alexn
alexn

Reputation: 59002

Check the second example in the documentation on popen, it shows exactly how to do that:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);

This snippet reads from stderr. Remove the pipe to read from stdout.

Upvotes: 13

Related Questions