Exec:

  • exec — Execute an external program

Description:

Php Code
string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command.

Example #1 

Php Code
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>
[ad type=”banner”]

shell_exec

  • shell_exec — Execute command via shell and return the complete output as a string

Description:

Php Code
string shell_exec ( string $cmd )

This function is identical to the backtick operator.

Example #2 :

Php Code
<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

A couple of distinctions that weren’t touched on here:

  • With this function, you can pass an optional param variable which will receive an array of output lines. In some cases this might save time, especially if the output of the commands is already tabular.

Compare:

Php Code
exec('ls', $out);
var_dump($out);
// Look an array
$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it
[ad type=”banner”]
  • Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you’ll need to post-process the input into some other form, so in that case use shell_exec.
  • It’s also worth pointing out that shell_exec is an alias for the backtick operator, for those used to *nix.
Php Code
$out = `ls`;
var_dump($out);
  • It also supports an additional parameter that will provide the return code from the executed command:
Php Code
exec('ls', $out, $status);
if (0 === $status) {
var_dump($out);
} else {
echo "Command failed with status: $status";
}

As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec.

Difference:

  • shell_exec – Execute command via shell and return the complete output as a string
  • exec – Execute an external program.

The difference is that with shell_exec you get output as a return value.

Categorized in: