kritya
kritya

Reputation: 3362

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";
sleep(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

Upvotes: 1

Views: 703

Answers (3)

Paul Dixon
Paul Dixon

Reputation: 300825

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.

Upvotes: 4

zerkms
zerkms

Reputation: 254916

Change your first script to:

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

Upvotes: 3

Paul
Paul

Reputation: 141839

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";
?>

Upvotes: 1

Related Questions