exec

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
zachsilvey
Forum Newbie
Posts: 3
Joined: Sun Nov 11, 2007 12:01 pm
Location: Battle Ground, WA, USA

exec

Post 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.
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: exec

Post 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);
 
User avatar
The_Anomaly
Forum Contributor
Posts: 196
Joined: Fri Aug 08, 2008 4:56 pm
Location: Tirana, Albania

Re: exec

Post 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.
Post Reply