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);
The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer initiated by the popen() function must be closed with pclose(). The command and the mode are sent as parameters to the popen() function and it returns a unidirectional file pointer on success or FALSE on failure.
popen(): on success, returns a pointer to an open stream that can be used to read or write to the pipe; if the fork(2) or pipe(2) calls fail, or if the function cannot allocate memory, NULL is returned.
The popen() function uses a program name as its first argument. The second argument is a file mode, such as "r" to read, "w" to write, or "r+" for both. Once opened, the same FILE type pointer is used as a reference.
The popen() function executes the command specified by the string command. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With