- exec — Execute an external program
exec() executes the given command.
Example #1 An exec() example
- passthru — Execute an external program and display raw output
- The passthru() function 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.
- A common use for this is to execute something like the pbmplus utilities that can output an image stream directly.
- By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.
- system — Execute an external program and display the output
- system() is just like the C version of the function in that it executes the given command and outputs the result.
- The system() call also tries to automatically flush the web server’s output buffer after each line of output if PHP is running as a server module.
- 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.
Example #2 system() example
exec() vs system() vs passthru()
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 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).