The PHP Function Shell_Exec
php function shell_exec is a powerful tool that allows you to execute external applications from within a PHP script. The function can be used to execute any command in the operating system that is accessible to PHP, including utilities such as ls and rm. The output of the executed command is captured and returned to the script. However, the security implications of executing an external application from PHP are significant and should be handled with caution.
The exec() function takes a command as a parameter and captures the output by returning it to the script in an array. It also returns the last line of the command output if echoed. It is important to note that if the command fails to execute, the error message will be displayed on the page.
In contrast, the shell_exec() function enables you to pass in a variable that will capture the entire result of an executed command. The variable can be updated as the command progresses. Unlike the exec() function, the shell_exec() function returns the value of the passed variable rather than NULL if an error is encountered.
The function accepts a single argument, $cmd, that holds the command that you wish to execute. The command is executed via the shell and returned as a string to the PHP script. The return code is stored in a variable ($return_var) and is updated as the command proceeds. The shell_exec() function supports the use of aliases for the command that is executed, which can be helpful if you are using the functions in an environment where aliases are allowed.