how get the output from process opend by popen in

2019-01-25 10:02发布

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);

标签: php popen
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-25 10:40

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.

查看更多
Emotional °昔
3楼-- · 2019-01-25 10:50

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.

查看更多
登录 后发表回答