Learn how to execute Linux shell commands in PHP using exec()
and shell_exec()
. Run system commands, capture output, and automate tasks securely.
Introduction
PHP can interact with the system shell to execute Linux or Windows commands, making it a powerful tool for automating server tasks, running scripts, and managing files.
With PHP, you can:
- Run shell commands dynamically using
exec()
andshell_exec()
- Capture command output and process it in PHP
- Execute background processes without blocking execution
- Securely run shell scripts with controlled access
This guide covers:
- Understanding
exec()
vsshell_exec()
- Running simple and complex shell commands in PHP
- Handling command output and errors
- Executing background tasks using PHP
- Securing PHP shell execution to avoid security risks
1. Difference Between exec() and shell_exec() in PHP
PHP provides two main functions to execute shell commands:
Function | Description | Returns |
---|---|---|
exec($command, $output, $return_var) |
Executes a command, captures output in an array | Output array or last line |
shell_exec($command) |
Runs a command and returns entire output as a string | String output |
Which One to Use?
- Use
exec()
when you need structured array-based output. - Use
shell_exec()
when you need the entire command output as a string.
2. Running Basic Shell Commands in PHP
Example 1: Using exec()
to List Files in a Directory
$output = [];
$return_var = 0;
exec('ls -la', $output, $return_var);
echo "<pre>";
print_r($output);
echo "</pre>";
What This Does:
- Executes the
ls -la
command in Linux - Stores the output as an array
- Displays directory listing in PHP
Example 2: Using shell_exec()
to Get System Uptime
$output = shell_exec('uptime');
echo "<pre>$output</pre>";
What This Does:
- Runs the
uptime
command - Displays server uptime information
3. Capturing and Processing Command Output in PHP
To capture command output and return status, use exec()
.
Example: Checking Disk Usage
exec('df -h', $output, $return_var);
if ($return_var === 0) {
echo "Command executed successfully!<br>";
echo "<pre>" . implode("\n", $output) . "</pre>";
} else {
echo "Error executing command!";
}
Why Use This?
- Allows error handling for failed commands
- Provides structured output for processing
4. Running Background Processes Without Blocking PHP
If a command needs to run in the background, append &
at the end.
Example: Running a Shell Script in the Background
exec('bash backup_script.sh > /dev/null 2>&1 &');
echo "Backup started in the background.";
What This Does:
- Runs
backup_script.sh
without blocking PHP execution - Redirects output to
/dev/null
to prevent PHP from waiting
5. Handling Errors and Command Failures in PHP
To detect errors when executing shell commands, use:
$output = shell_exec('invalid_command 2>&1');
echo "<pre>$output</pre>";
What This Does:
- Captures error messages from failed commands
For structured error handling, use exec()
:
exec('invalid_command 2>&1', $output, $return_var);
if ($return_var !== 0) {
echo "Error: " . implode("\n", $output);
} else {
echo "Command executed successfully!";
}
6. Running PHP Scripts from the Shell
To run a PHP script from the terminal, use:
php myscript.php
To execute a PHP script from another PHP script via shell:
$output = shell_exec('php another_script.php');
echo "<pre>$output</pre>";
This allows one PHP script to call another script dynamically.
7. Executing Bash Scripts from PHP
To run a Bash script from PHP:
$output = shell_exec('bash myscript.sh');
echo "<pre>$output</pre>";
To pass arguments:
$arg1 = "backup";
$output = shell_exec("bash myscript.sh $arg1");
echo "<pre>$output</pre>";
Why Use This?
- Enables integration of PHP with shell automation
- Allows dynamic execution of server scripts
8. Securely Running Shell Commands in PHP
Running shell commands can be dangerous if not handled properly.
Avoid User Input in Shell Commands
Never execute user-provided input directly in exec()
or shell_exec()
.
Unsafe Example (DO NOT USE):
$filename = $_GET['file'];
exec("rm -rf $filename"); // Dangerous, allows remote execution!
Safe Example (Use Escaping):
$filename = escapeshellarg($_GET['file']);
exec("rm -rf $filename"); // Secured against command injection
Disable Shell Execution for Security
If shell execution is not needed, disable it in php.ini
:
disable_functions = exec, shell_exec, system, passthru
Use sudo
Only When Necessary
To execute privileged commands securely, configure sudoers
for PHP.
sudo visudo
Add:
www-data ALL=(ALL) NOPASSWD: /path/to/script.sh
Then, execute in PHP:
$output = shell_exec('sudo bash /path/to/script.sh');
echo "<pre>$output</pre>";
9. Running Commands on Remote Servers Using SSH in PHP
To execute shell commands on a remote server, use SSH:
$server = 'user@192.168.1.100';
$command = 'ls -la';
$output = shell_exec("ssh $server '$command'");
echo "<pre>$output</pre>";
To use password authentication, install sshpass
and modify:
$output = shell_exec("sshpass -p 'password' ssh user@192.168.1.100 'ls -la'");
Why Use This?
- Enables remote server management from PHP
- Useful for deployments, backups, and remote administration
Best Practices for Running Shell Commands in PHP
- Use
exec()
for structured output,shell_exec()
for full output - Escape user input with
escapeshellarg()
to prevent security risks - Avoid running shell commands as root unless necessary
- Run background processes (
&
) for long-running tasks - Securely execute commands with
sudoers
configuration
Conclusion
With exec()
and shell_exec()
, PHP can execute system commands, manage files, run background tasks, and automate server administration.
This guide covered:
- Running shell commands in PHP
- Capturing and handling command output
- Executing background processes and Bash scripts
- Implementing security best practices
By implementing these techniques, PHP applications can interact with system shells effectively and securely.