PHP: How to execute shell commands with shell_exec()

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

In the realm of server-side scripting, PHP is a powerhouse that’s often interfaced with the system it resides on. Interacting with the underlying operating system can provide powerful functionality for applications. One such interface is the execution of shell commands. In this tutorial, we’ll take an in-depth look into shell_exec(), a PHP function used to execute commands via the shell and collect the complete output directly from PHP.

Prerequisites

  • A server or local development environment running PHP
  • Basic knowledge of PHP syntax and functions
  • Familiarity with shell commands

Understanding shell_exec()

The syntax of shell_exec() is straightforward:

string shell_exec ( string $cmd )

This function takes one parameter: $cmd, which is the command line you want to execute as a string. It returns the entire output as a string or NULL on an error or if the command does not yield an output.

Implementing shell_exec()

Let’s begin with basic usage:

$output = shell_exec('ls -lart');
echo $output;

This will list files in the current directory in a detailed, reverse chronological order.

Best Practices for Security

Security should not be an afterthought when using shell_exec():

  • Always validate and sanitize input that will be part of shell commands.
  • Limit the commands allowed to be executed.
  • Consider using higher-level PHP functions where possible instead of shell commands.

Error Handling and Diagnostics

shell_exec() does not return stderr. To capture errors, you can redirect stderr to stdout:

$output = shell_exec('somecommand 2>&1');

This will ensure error messages are captured in the output.

Alternatives to shell_exec()

If you need more control over execution or desire to work with the process I/O in real-time, consider the following functions:

  • exec() – Execute a single shell command and optionally collect the last line of output.
  • passthru() – Execute a command and directly send raw output to the browser.
  • system() – Execute a shell command with full output and return status.
  • proc_open() – Provides thorough control over process execution, including stdin, stdout, and stderr streams.

Common Use Cases and Examples

Beyond listing files, here’s how you might use shell_exec() for more complex tasks:

Running a Python Script

$output = shell_exec('python /path/to/script.py');

Pinging a Server

$domain = escapeshellarg('example.com'); //$domain is now safe to use in the shell command
$output = shell_exec('ping -c 4 ' . $domain);

Conclusion

In this tutorial, we covered the shell_exec() function in PHP, including its syntax, usage, security concerns, and potential alternatives. While it’s a powerful tool, always approach shell commands with security as a priority and respect PHP’s higher-level functions whenever possible.