Don
Don

Reputation: 235

PHP exec returns "array" instead of the result of my command

I'm trying to build a web terminal emulator on my local webserver (openwrt), every time I execute the command, the result always says "array", for instance when I execute uptime it doesn't give me the up time of my webserver but instead it gives me array. This is my script:

<?php
..............................
if($_POST['command'])
{
$command = $_POST['command'];
exec("$command 2>&1 &", $output);
echo $command;
}
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "Command:<br><input type=\"text\" autofocus name=\"command\" size=\"15\" value=\"\"/><br>";
echo '<br>Result :<br><pre>
        <div id="show" style="font-size: 11px;  word-wrap: break-word; width:550px;height:200px;border:0px solid #000;text-align:left; overflow-y: scroll;">
        '.$output.'</div>';
echo '<input type="submit" name="kill" value="Kill Command" />';
echo "</form></div>";
.........................
?>

I want the $output to return the result of my command. Right now, the $output always returns array no matter what type of command I execute, how should I fix this?

Upvotes: 4

Views: 12678

Answers (2)

Dipu Raj
Dipu Raj

Reputation: 1884

Option 1: You can use implode to combine the array result to a string.

exec("$command 2>&1 &", $output);
echo implode(PHP_EOL, $output);

Option 2: You can use shell_exec which return the complete output as a string.

echo shell_exec("$command 2>&1 &");

Upvotes: 2

Attila Fulop
Attila Fulop

Reputation: 7011

It is supposed to return an array as it is written in the documentation.

If you want to print the array line by line use a code like this:

<?php
exec("$command 2>&1 &", $output);
foreach ($output as $line) {
    echo "$line\n";
}

Upvotes: 9

Related Questions