What’s the difference between exec(), passthru(), shell_exec(), and system()?

Did you ever wonder what the difference is between exec(), passthru(), shell_exec(), and system()? Why are there so many functions that seem to do the same thing? Let’s start by looking at what php.net has to say about them:

exec

Execute an external program

passthru

Execute an external program and display raw output

shell_exec

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

system

Execute an external program and display the output

So what’s the difference?

00074If we dig into the question further we find that there are some subtle but important differences in the way that these functions return data.

exec() returns only the last line of the result of the command it is given. This is because the return value is not the purpose of exec(). Instead you should use the second parameter $output, which is an array that will have each line of the result appended to it. If you call exec multiple times (in a loop for example), all of the output will be added to the same array. This is the main use case for exec(), when you want to fill an array with the output form a command, like a list: exec(‘ls -l’,$file_list);

passthru() is a very useful tool for debugging php over the command line. This function will pass the raw output along and display error messages along with output from echo. If you are dealing with a remote php file and its not working, this will usually tell you why.

shell_exec() is your standard execution function. It outputs in a way that most developers would expect (I think). It simply passes the result of the command through the return value. For running basic commands, this is your function. It can also be run shorthand using the backtick operator.

system() will echo the result of the command rather than passing it in the return value. It will, however, pass the last line of the result into the return value, and like exec() it can take an extra parameter $return_var that will be filled with the integer return status of the command after it is executed. If you want to capture output for debugging purposes, you can pass stderr to stdout by adding 2>&1 to the end of any command.

So in conclusion, use shell_exec() for most simple tasks, but use the others when special cases arise.

Security

Don’t forget to escape any user input that is passed to a command with escapeshellarg() or escapeshellcmd(). This is important because it will prevent users from executing commands directly on your server!

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *