开发者

allow php invoked by exec() to write to console

I invoked a php file by exec() doing this :

<?php
$cmd = "php -q nah.php";
exec($cmd);
echo "lalal";
?>

and the nah.php has this :

<?php
echo "yaya";
s开发者_如何学JAVAleep(3);
?>

It does sleep for 3 seconds but the file can echo out to the command. How can I do echo the output from nah.php


If you want to capture the output of another process, then you can use backticks

$output=`command line`;

or capture it with exec()

exec('command line', $output);

However, both of these techniques only give the output when the external process has run to completion. If you want to grab the output as it happens, you can use popen (or proc_open for more control), e.g. something like this

$handle = popen('command line 2>&1', 'r');
while (!feof($handle))
{
    $read = fread($handle, 2096);
    echo $read;
}
pclose($handle);

The 2>&1 at the end of the command line is a handy idiom if running within a shell like bash. It redirects stderr to stdout, so any errors the command generates will be returned to PHP. There are more advanced ways to capture stderr, this just makes it easy.


Change your first script to:

<?php
$cmd = "php -q nah.php";
echo `$cmd`;
echo "lalal";


exec() creates a new console and executes the php file there, it returns the output in an array (One element per line return) that is passed in as a second argument. So if you change your code to:

<?php
$output = array();
$cmd = "php -q nah.php";
exec($cmd, $output);
$lines = count($output);
for($i = 0; $i < $lines; $i++)
  echo $output[$i];
echo "lalal";
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜