Page 1 of 1

exec

Posted: Sat Aug 16, 2008 4:20 pm
by zachsilvey
I am using this to store the output of a command to a array.

Code: Select all

$command = 'ls';
$output = exec($command, $output, $return);
print $output;
Can someone please tell me why only the last line of the output is stored in the array.

Re: exec

Posted: Sat Aug 16, 2008 5:05 pm
by EverLearning
From PHP manual for exec()
string exec ( string $command [, array &$output [, int &$return_var ]] )

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
So basically with

Code: Select all

$output = exec($command, $output, $return);
you're overwriting the array $output(which you passed as the second argument to the exec function)with the return value of the exec() which as stated above returns the last line from the result.

Use

Code: Select all

$output = array();
exec($command, $output, $return);
var_dump($output);
 

Re: exec

Posted: Sat Aug 16, 2008 5:14 pm
by The_Anomaly
zachsilvey wrote:I am using this to store the output of a command to a array.

Code: Select all

$command = 'ls';
$output = exec($command, $output, $return);
print $output;
Can someone please tell me why only the last line of the output is stored in the array.
From what I understand, the exec function returns a string which is the last line of the output. That's overwriting the array of output you defined in the second argument of exec. Try this:

Code: Select all

<?php
exec('{command}',$return);
foreach($return as $return_lo){
    echo $return_lo;
}
?>
That will loop through the array of output, and echo the results. Check out this page.

EDIT: Beaten, with probably a better solution.