Tuesday, May 13, 2008

exec and shell_exec

In php, both exec() and shell_exec() are used to execute shell commands. When to use which one?

shell_exec() is same as backtick operator. i.e.

echo `ls -l`; is same as
$r = shell_exec("ls -l"); echo $r;

use this when you don't need the return value (0 or some number) of the command.


exec() takes three parameters:
1. command
2. address of the array where the output will be stored
3. address of a integer variable in which the return value will be stored
e.g:

$output = array();
exec("ls -l", &$output, &$ret);

exec returns only the last line of the output, so if you need to process the output, use the $output array.

Here are the manuals for shell_exec and exec.

No comments: