ChatGPT解决这个技术问题 Extra ChatGPT

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

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 that they are used to execute external programs. see reference From the examples I see, I don't see any obvious difference.

If I were to simply run a script (bash or python), which function do you recommend me to use?

There's also proc_open() and popen(), both of which allow a higher degree of control over the spawned process.

Z
ZioCain

They have slightly different purposes.

exec() is for calling a system command, and perhaps dealing with the output yourself.

system() is for executing a system command and immediately displaying the output - presumably text.

passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.


Sometimes portability has to be sacrificed for functionality. There are some things PHP just can't do well.
@Kalium: can you elaborate more on your statement? just stating some vague percentage statistics does not convince me. I believe that using system calls to execute scripts are totally fine as long as the whole application does not depend one a bunch of scripts in the back-end.
@Christian izkata@izein:~$ dir -bash: dir: command not found - FreeBSD
@OZ_ I've come to the situation where I had to do very expensive computations. No PHP-Module were (is) available for that. I wrote my own C program and I invoke it with passthru(). Sometimes portability can be less important than other things. Depends on the project.
Also, it's a fallacy to think that PHP is portable as long as you avoid exec, system, passthru. PHP code is reliant on the environment it runs in, and many security bugs are due to not having this in consideration. Here's a quick example: stackoverflow.com/questions/3003145/…
5
5 revs, 2 users 89%

As drawn from http://php.net/ && Chipmunkninja:

The system() Function The system function in PHP takes a string argument with the command to execute as well as any arguments you wish passed to that command. This function executes the specified command, and dumps any resulting text to the output stream (either the HTTP output in a web server situation, or the console if you are running PHP as a command line tool). The return of this function is the last line of output from the program, if it emits text output. The exec() Function The system function is quite useful and powerful, but one of the biggest problems with it is that all resulting text from the program goes directly to the output stream. There will be situations where you might like to format the resulting text and display it in some different way, or not display it at all. For this, the exec function in PHP is perfectly adapted. Instead of automatically dumping all text generated by the program being executed to the output stream, it gives you the opportunity to put this text in an array returned in the second parameter to the function: The shell_exec() Function Most of the programs we have been executing thus far have been, more or less, real programs1. However, the environment in which Windows and Unix users operate is actually much richer than this. Windows users have the option of using the Windows Command Prompt program, cmd.exe This program is known as a command shell. The passthru() Function One fascinating function that PHP provides similar to those we have seen so far is the passthru function. This function, like the others, executes the program you tell it to. However, it then proceeds to immediately send the raw output from this program to the output stream with which PHP is currently working (i.e. either HTTP in a web server scenario, or the shell in a command line version of PHP). The proc_open() Function and popen() function proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.


shell_exec execution speed is faster than other alternate.
You should mention that you've copied your answer directly from ChipmunkNinja.
@TachyonVortex luckily he did copy the answer verbatim, because ChipmunkNinja no longer exists.
There is a copy of that article in the wayback machine: web.archive.org/web/20130809032648/http://chipmunkninja.com/…
What about popen and proc_open?
N
Norbert Wagner

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.


which ones can execute a php file?
@johnywhy none per se - unless you explicitly invoke the php cli or such. I suppose you want include and friends
This table is the best summary of these commands.
k
kenorb

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

exec executes a command and passes output to the caller (or returns it in an optional variable).

passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.


Be also aware that exec could do a loop in some versions of php. see stackoverflow.com/questions/3615713/…
t
the

If you're running your PHP script from the command-line, passthru() has one large benefit. It will let you execute scripts/programs such as vim, dialog, etc, letting those programs handle control and returning to your script only when they are done.

If you use system() or exec() to execute those scripts/programs, it simply won't work.

Gotcha: For some reason, you can't execute less with passthru() in PHP.


I don't understand what you're saying. You can execute programs both from CLI and (F)CGI (as well as mod_php). There may be system-imposed restrictions, such as selinux. But a well set-up system will have those selectively off. Of course a shared host is a different story, but you won't offer a shared environment to esteemed clients either, no?