68

It is possible to run an external command by three PHP functions of

system();
exec();
shell_exec();

but what are their differences? In spite of their specific applications, in most cases, the can be equally used. I am curious to know which is preferred one when they can be equally used. For example, for unzipping a file or compressing a folder (with tar command), which one is preferred (probably from performance point of view)?

UPDATE: In another question, I found a very useful link describing different aspects for these functions. I share the link here, as other may use to better understand security issues and other aspects.

the
  • 21,007
  • 11
  • 68
  • 101
Googlebot
  • 15,159
  • 44
  • 133
  • 229
  • 5
    Not to be snippy, but what did the manual say about the respective functions? – GordonM May 31 '12 at 06:54
  • 2
    Also, you forgot passthru () :) – GordonM May 31 '12 at 06:55
  • @GordonM I read the manual, but I do not understand the preference for each function. For many cases, they can be equally used. I want a practical view. – Googlebot May 31 '12 at 06:59
  • 1
    Possible duplicate of http://stackoverflow.com/questions/732832/php-exec-vs-system-vs-passthru – periklis May 31 '12 at 07:26
  • @periklis you're right, that question addresses the same issue, but I was unable to find it. One answer has a quite useful link for detailed explanations. Thanks! – Googlebot May 31 '12 at 07:40
  • Possible duplicate of [PHP exec() vs system() vs passthru()](https://stackoverflow.com/q/732832/608639) and [php shell\_exec() vs exec()](https://stackoverflow.com/questions/7093860/php-shell-exec-vs-exec) – jww Feb 21 '18 at 07:18
  • Does this answer your question? [PHP exec() vs system() vs passthru()](https://stackoverflow.com/questions/732832/php-exec-vs-system-vs-passthru) – Nico Haase Apr 07 '22 at 14:08

1 Answers1

93

exec — Execute an external program

system — Execute an external program and display the output

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

so if you don't need the output, I would go with exec.

Further details:

Gras Double
  • 15,901
  • 8
  • 56
  • 54
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • 7
    `exec()` returns the last line of output, so if you're calling a simple program that just outputs a single value like `whoami` or `pwd`, `exec()` is perfect. – alanaktion Dec 02 '15 at 20:54