Current Location: Home> Function Categories> shell_exec

shell_exec

Execute commands through the shell environment and return the complete output as a string
Name:shell_exec
Category:Program execution
Programming Language:php
One-line Description:Execute the specified shell command and return the output of the command as a string

Function name: shell_exec()

Applicable version: PHP 4, PHP 5, PHP 7

Function description: The shell_exec() function executes the specified shell command and returns the output of the command as a string. Unlike the exec() function, the shell_exec() function returns the complete result of the command output, not just the last line.

Syntax: shell_exec ( string $cmd ) : string|NULL

parameter:

  • $cmd: Required, shell command to be executed.

Return value:

  • If the command is executed successfully, the string result output by the command is returned.
  • If the command fails to execute or the function is disabled, NULL is returned.

Example 1:

 $output = shell_exec('ls -l'); echo "<pre>$output</pre>";

The above example executes the "ls -l" command and assigns the result to the $output variable. Then, use the <pre> tag to output the result as is to the browser.

Example 2:

 $output = shell_exec('php -v'); echo "<pre>$output</pre>";

The above example will execute the "php -v" command, display the PHP version information, and assign the result to the $output variable. Then, use the <pre> tag to output the result as is to the browser.

Notes:

  1. The shell_exec() function depends on the operating system availability when executing shell commands, so different results may occur on different operating systems.
  2. For security reasons, the shell_exec() function should be used with caution and only trusted commands are allowed to be executed.
  3. When using the shell_exec() function, you need to make sure that the function is not disabled in the PHP configuration file (disable_functions configuration item).
  4. In some cases, it may be necessary to use an absolute path to execute commands such as '/usr/bin/ls'.
  5. If the command requires user input, use other functions (such as exec() or passthru()), because the shell_exec() function does not support interaction with the shell process.
Similar Functions
Popular Articles