exec()

exec() — Execute an external program.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

Signature

exec(string $command, array &$output = null, int &$result_code = null): string|false

Parameters

ParameterTypeWhat it takes
$commandstringThe command that will be executed.
&$outputarrayIf the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
&$result_codeintIf the result_code argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return value

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function. Returns false on failure. To get the output of the executed command, be sure to set and use the output parameter.

Example

A runnable snippet:

// outputs the username that owns the running php/httpd process // (on a system with the "whoami" executable in the path) exec('whoami', $output, $result_code); echo "Returned with status $result_code and output:\n"; print_r($output);

Output:

Returned with status 0 and output: Array ( [0] => cmb )

Changelog

VersionChange
8.0.0If command is empty or contains null bytes, exec() now throws a ValueError. Previously it emitted an E_WARNING and returned false.

See also

system(), passthru(), escapeshellcmd()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page exec() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.