LX DevBlog

About

Execute Shell Command in PHP

1/9/2024
PHP

PHP has a backtick operator.

Anything between ` ` will be executed like shell_exec and returned.

echo 'Hi, I am ' . `whoami`
echo `curl https://www.php.net`

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.

string shell_exec( $cmd )

Parameters: This function accepts single parameter $cmd which is used to hold the command that will be executed.

The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.

string exec( $command, $output, $return_var )

Parameters: This function accepts three parameters as mentioned above and described below:

  • $command: This parameter is used to hold the command which will be executed.
  • $output: This parameter is used to specify the array which will be filled with every line of output from the command.
  • $return_var: The $return_var parameter is present along with the output argument, then it returns the status of the executed command will be written to this variable.

Return Value: This function returns the executed command, be sure to set and use the output parameter.