A couple of distinctions that weren't touched on here:
- With exec(), 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:
exec('ls', $out);
var_dump($out);
// Look an array
$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it
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 backtic operator, for those used to *nix.
$out = `ls`;
var_dump($out);
exec also supports an additional parameter that will provide the return code from the executed command:
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.
date
,whoami
,ifconfig
,netstat
. – user1585852