Learn how to execute a Bash script from PHP using shell_exec()
, exec()
, and proc_open()
. Run shell scripts securely and handle output effectively.
Introduction
Executing Bash scripts from PHP enables automation of file handling, backups, server monitoring, and deployments. Instead of running shell commands manually, PHP can trigger Bash scripts dynamically, making server management efficient.
With PHP and Bash, you can:
- Automate server tasks using scheduled scripts
- Execute Bash commands from PHP
- Pass arguments to Bash scripts dynamically
- Handle script output and errors
This guide covers:
- Executing Bash scripts using
shell_exec()
,exec()
, andproc_open()
- Passing arguments and handling script output
- Running Bash scripts in the background
- Securing PHP-Bash execution to prevent security risks
1. Running a Bash Script Using shell_exec()
The shell_exec()
function runs shell commands and captures output.
Example: Executing a Bash Script from PHP
$output = shell_exec('bash /path/to/myscript.sh');
echo "<pre>$output</pre>";
What This Does:
- Runs
myscript.sh
from PHP - Captures script output
- Displays the output in a readable format
2. Using exec() to Execute a Bash Script
The exec()
function provides more control over output and error handling.
Example: Running a Script and Capturing Output
$output = [];
$returnVar = 0;
exec('bash /path/to/myscript.sh', $output, $returnVar);
if ($returnVar === 0) {
echo "Script executed successfully.<br>";
echo "<pre>" . implode("\n", $output) . "</pre>";
} else {
echo "Error executing script.";
}
Why Use exec()?
- Returns an array of output lines
- Captures the exit status of the Bash script
3. Passing Arguments to a Bash Script from PHP
Example: Running a Bash Script with Parameters
$filename = 'backup_' . date('Y-m-d') . '.zip';
$output = shell_exec("bash /path/to/backup.sh $filename");
echo "<pre>$output</pre>";
Example Bash Script (backup.sh
)
#!/bin/bash
echo "Creating backup: $1"
tar -czf /backups/$1 /var/www/html/
echo "Backup completed."
What This Does:
- PHP passes a dynamic filename to the Bash script
- The Bash script processes the input and performs an action
4. Running a Bash Script in the Background
If a script takes a long time to execute, run it in the background.
exec('bash /path/to/myscript.sh > /dev/null 2>&1 &');
echo "Script started in the background.";
Why Use This?
- Prevents PHP from waiting for script completion
- Useful for long-running tasks like backups
5. Handling Errors When Running Bash Scripts
To capture errors inside PHP, redirect STDERR (2>&1
).
$output = shell_exec('bash /path/to/error_script.sh 2>&1');
echo "<pre>$output</pre>";
Inside the Bash script (error_script.sh
):
#!/bin/bash
echo "This is a test error" >&2
exit 1
What This Does:
- Captures error messages from the Bash script
- Returns error status to PHP
6. Running PHP Scripts Inside a Bash Script
If Bash needs to run a PHP script, use:
#!/bin/bash
php /var/www/html/script.php
To run PHP scripts in the background:
nohup php /var/www/html/script.php > /dev/null 2>&1 &
Why Use This?
- Enables Bash scripts to trigger PHP scripts
- Useful for chained automation tasks
7. Securely Executing Bash Scripts from PHP
Avoid Executing User Input Directly
Unsafe Example (DO NOT USE):
$filename = $_GET['file'];
shell_exec("bash /scripts/delete.sh $filename"); // Unsafe!
Safe Example (Escaping User Input):
$filename = escapeshellarg($_GET['file']);
shell_exec("bash /scripts/delete.sh $filename"); // Secured
Restricting PHP from Running System Commands
To prevent unauthorized execution, disable shell functions in php.ini
:
disable_functions = exec, shell_exec, system, passthru
Using Sudo Securely
To execute privileged scripts, configure sudoers
:
sudo visudo
Add the following line:
www-data ALL=(ALL) NOPASSWD: /path/to/script.sh
Then execute the script in PHP:
$output = shell_exec('sudo bash /path/to/script.sh');
echo "<pre>$output</pre>";
8. Running Bash Scripts on a Remote Server Using SSH
To execute a script on a remote Linux server, use SSH:
$server = 'user@192.168.1.100';
$output = shell_exec("ssh $server 'bash /path/to/myscript.sh'");
echo "<pre>$output</pre>";
To use password authentication, install sshpass
:
$output = shell_exec("sshpass -p 'password' ssh user@192.168.1.100 'bash /path/to/myscript.sh'");
echo "<pre>$output</pre>";
Why Use This?
- Automates remote deployments and server management
- Executes Bash scripts across multiple servers
9. Running Bash Scripts on a Schedule with Cron Jobs
To automate script execution, schedule a cron job:
crontab -e
Add a scheduled task to run the script every night at midnight:
0 0 * * * php /var/www/html/automate.php
To log execution results:
0 0 * * * php /var/www/html/automate.php >> /var/log/cron.log 2>&1
10. Best Practices for Running Bash Scripts in PHP
- Use
shell_exec()
for direct execution and capturing output - Use
exec()
when error handling is required - Escape user input with
escapeshellarg()
to prevent security risks - Run scripts in the background for long tasks
- Use SSH for remote execution instead of storing passwords in PHP
Conclusion
Executing Bash scripts from PHP enables server automation, file management, backups, and deployments.
This guide covered:
- Using
shell_exec()
andexec()
to run Bash scripts - Passing arguments to scripts dynamically
- Executing long-running scripts in the background
- Handling errors and security best practices
- Running Bash scripts remotely using SSH
By following these techniques, PHP applications can efficiently automate server tasks using Bash scripts.