PHP exec() vs system() vs passthru()

前端 未结 5 1043
别那么骄傲
别那么骄傲 2020-11-22 10:34

What are the differences?

Is there a specific situation or reason for each function? If yes, can you give some examples of those situations?

PHP.net says tha

5条回答
  •  无人及你
    2020-11-22 10:44

    The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

    +----------------+-----------------+----------------+----------------+
    |    Command     | Displays Output | Can Get Output | Gets Exit Code |
    +----------------+-----------------+----------------+----------------+
    | system()       | Yes (as text)   | Last line only | Yes            |
    | passthru()     | Yes (raw)       | No             | Yes            |
    | exec()         | No              | Yes (array)    | Yes            |
    | shell_exec()   | No              | Yes (string)   | No             |
    | backticks (``) | No              | Yes (string)   | No             |
    +----------------+-----------------+----------------+----------------+
    
    • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
    • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
    • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

    Other misc things to be aware of:

    • The shell_exec() and the backticks operator do the same thing.
    • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
    • Add "2>&1" to the command string if you also want to capture/display error messages.
    • Use escapeshellcmd() to escape command arguments that may contain problem characters.
    • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.

提交回复
热议问题