b.php file:

How to get output from opend process by popen in php?

a.php file:

<?php echo "abcdef"; ?> 

b.php file:

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

Question:

I do not see the result of the echo on the console; why and how to see it?

I do not want to do this in a b.php file like: echo stream_get_contents($h);

+10
php popen
source share
3 answers

Check out the second example in the popen documentation, it shows exactly how to do this:

 <?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 is read from stderr. Remove the reading tube from the standard output.

+8
source share

You cannot see the echo result on the console because it never got on the console. Having opened the process in read mode, its STDOUT was associated with the file handle of the open process. The only way to get console output would be if you read the file from this file descriptor and then repeat it.

The flow, in other words, is this.

  • b.php starts working - its STDIN and STDOPUT are connected to your console as usual
  • it calls popen in read mode and saves the stream resource in $ h
  • this causes a.php to start, with its STDOUT associated with the file descriptor in $ h, and its STDIN not tied to anything
  • this means that, as you can see, a.php does not have direct access to the console from which b.php was launched.
  • a.php writes its output to this stream and then finishes executing
  • b.php never does anything with a stream in $ h, it just closes it, so the output of a.php is lost.

Hope this explains what is happening 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, and then repeat it, since only b.php has access to the console.

Alternatively, if you use system () instead of popen (), the output will be displayed in the calling console script automatically, since using system () passes the main script STDIN and STOUT to the program or script that you are calling.

+4
source share

try it:

 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(); } 
0
source share

All Articles