PHP provides the exec() method in order to execute or run commands, programs, or scripts. This exec() method can simply execute external commands in the operating system. For example, the whoami command of Linux can be executed for the current user, and returned username can be used in PHP applications.
The exec() Method Syntax
The PHP exec() method has the following syntax.
exec(string $command, array &$output, int &$result_code)
- $command is a string type which is the command string representation.
- &$output is a array variable where the executed command result is stored.
- &$result_code is an int which stores the command result code as integer.
The exec() method returns false boolean value or string where strinh is the last line of the output.
Execute Command
We will start with a simple example. We execute the “whoami” command in the Linux system and store the result or output in the variable named $output.
<?php
$output = null;
$code = null;
exec("whoami",$output,$code);
print_r($output)
?>
Alternatively we can provide the command we want to execute as a string variable like below. In the following example we set the command into the variable named $command.
<?php
$output = null;
$code = null;
$command = "whoami";
exec($command,$output,$code);
print_r($output)
?>
The whoami is very simple command which returns a single item which is the username of the current user. The exec() command can execute different commands which return more complext results. The “ls” command lists current working directory files and folders.
<?php
$output = null;
$code = null;
$command = "ls";
exec($command,$output,$code);
print_r($output);
?>
Array ( [0] => a.out [1] => cities.txt [2] => config.ttxt [3] => data1 [4] => data2 [5] => data3 [6] => data4 [7] => data5 ... [40] => text.txt [41] => thinclient_drives [42] => uniqip.txt [43] => userinput.py [44] => usomlist.txt [45] => Videos [46] => while.sh [47] => year )
We can see the output that is has total 47 items. The output stores each item with an index number. The output contains current working directory contents.
Execute Commands with Options and Parameters
The exec() method can be used to execute and run commands with options and parameters. It is the same way where the options and parameters set inside the command string. In the following example the “ls” command executed with the “-l” option and “/etc” parameter.
<?php
$output = null;
$code = null;
$command = "ls -l /var/log";
exec($command,$output,$code);
print_r($output);
?>

Execute Bash Script
The exec() method can be also used to execute bash commands scripts easily. Just provide the script name if it is located in the current working directory or specify the full path to prevent errors.
<?php
$output = null;
$code = null;
$command = "/home/ismail/backup.sh";
exec($command,$output,$code);
print_r($output);
?>