Exec:

  • exec — Execute an external program

Description:

[pastacode lang=”php” manual=”string%20exec%20(%20string%20%24command%20%5B%2C%20array%20%26%24output%20%5B%2C%20int%20%26%24return_var%20%5D%5D%20)” message=”Php Code” highlight=”” provider=”manual”/]

exec() executes the given command.

Example #1 

[pastacode lang=”php” manual=”%3C%3Fphp%0A%2F%2F%20outputs%20the%20username%20that%20owns%20the%20running%20php%2Fhttpd%20process%0A%2F%2F%20(on%20a%20system%20with%20the%20%22whoami%22%20executable%20in%20the%20path)%0Aecho%20exec(‘whoami’)%3B%0A%3F%3E” message=”Php Code” highlight=”” provider=”manual”/] [ad type=”banner”]

shell_exec

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

Description:

[pastacode lang=”php” manual=”string%20shell_exec%20(%20string%20%24cmd%20)%0A%0A” message=”Php Code” highlight=”” provider=”manual”/]

This function is identical to the backtick operator.

Example #2 :

[pastacode lang=”php” manual=”%3C%3Fphp%0A%24output%20%3D%20shell_exec(‘ls%20-lart’)%3B%0Aecho%20%22%3Cpre%3E%24output%3C%2Fpre%3E%22%3B%0A%3F%3E” message=”Php Code” highlight=”” provider=”manual”/]

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:

[pastacode lang=”php” manual=”exec(‘ls’%2C%20%24out)%3B%0Avar_dump(%24out)%3B%0A%2F%2F%20Look%20an%20array%0A%24out%20%3D%20shell_exec(‘ls’)%3B%0Avar_dump(%24out)%3B%0A%2F%2F%20Look%20–%20a%20string%20with%20newlines%20in%20it” message=”Php Code” highlight=”” provider=”manual”/] [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.
[pastacode lang=”php” manual=”%24out%20%3D%20%60ls%60%3B%0Avar_dump(%24out)%3B” message=”Php Code” highlight=”” provider=”manual”/]
  • It also supports an additional parameter that will provide the return code from the executed command:
[pastacode lang=”php” manual=”exec(‘ls’%2C%20%24out%2C%20%24status)%3B%0Aif%20(0%20%3D%3D%3D%20%24status)%20%7B%0A%20%20%20%20var_dump(%24out)%3B%0A%7D%20else%20%7B%0A%20%20%20%20echo%20%22Command%20failed%20with%20status%3A%20%24status%22%3B%0A%7D” message=”Php Code” highlight=”” provider=”manual”/]

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: