What is different between exec(), shell_exec, system() and passthru() functions in PHP?

Learn what is different between exec(), shell_exec, system() and passthru() functions in php? with practical examples, diagrams, and best practices. Covers php development techniques with visual ex...

Understanding PHP's External Command Execution Functions: exec(), shell_exec(), system(), and passthru()

Hero image for What is different between exec(), shell_exec, system() and passthru() functions in PHP?

Explore the differences, use cases, and security considerations of PHP's functions for executing external commands: exec(), shell_exec(), system(), and passthru().

PHP provides several functions to execute external programs and shell commands. While they all serve the primary purpose of interacting with the operating system's command line, they differ significantly in how they handle input, output, and return values. Understanding these distinctions is crucial for choosing the right function for your task and, more importantly, for writing secure and efficient PHP applications.

Overview of PHP's Command Execution Functions

Each function offers a unique approach to command execution, catering to different scenarios. Let's break down their core functionalities before diving into the specifics.

flowchart TD
    A[PHP Script] --> B{Execute External Command}
    B -->|Output Handling| C[exec()]
    B -->|Return String| D[shell_exec()]
    B -->|Direct Output| E[system()]
    B -->|Raw Output| F[passthru()]
    C --> G["Returns last line of output, populates array with all lines"]
    D --> H["Returns full output as a single string"]
    E --> I["Prints output directly, returns last line"]
    F --> J["Prints raw output directly, returns nothing"]
    G --> K[Output to PHP variable]
    H --> K
    I --> L[Output to browser/console]
    J --> L

High-level overview of PHP command execution functions and their output handling.

exec(): Executing a Command and Capturing Output

The exec() function executes an external program and returns the last line of the command's output. Optionally, it can capture all lines of output into an array and retrieve the command's return status. This makes it suitable for scenarios where you need to process the output line by line or check the command's exit code.

<?php
$command = 'ls -l'; // Example command
$output = [];
$return_var = 0;

exec($command, $output, $return_var);

echo "<pre>";
echo "Last line of output: " . end($output) . "\n";
echo "All output:\n";
print_r($output);
echo "Return status: " . $return_var . "\n";
echo "</pre>";
?>

Using exec() to list directory contents and capture output.

shell_exec(): Retrieving Full Command Output as a String

Unlike exec(), shell_exec() executes a command via the shell and returns the complete output of the command as a single string. This is particularly useful when you need to capture the entire output for parsing or display without needing line-by-line processing or the exit status.

<?php
$command = 'cat /etc/os-release'; // Example command
$output = shell_exec($command);

if ($output === null) {
    echo "<p>Command failed or returned no output.</p>";
} else {
    echo "<pre>{$output}</pre>";
}
?>

Using shell_exec() to get the operating system release information.

system(): Direct Output and Return Status

The system() function is designed to execute an external program and display the raw output directly to the browser or standard output. It also returns the last line of the command's output and can optionally provide the command's return status. This function is often used when the output needs to be immediately visible to the user, similar to how a command-line interface works.

<?php
$command = 'ping -c 4 localhost'; // Example command
$return_var = 0;

echo "<pre>";
$last_line = system($command, $return_var);
echo "</pre>";

echo "<p>Last line of output (from return value): {$last_line}</p>";
echo "<p>Return status: {$return_var}</p>";
?>

Using system() to ping localhost and display output directly.

passthru(): Raw Output for Binary Data

The passthru() function executes an external program and passes its raw output directly to the browser without any PHP processing. This is especially useful for commands that generate binary data, such as image manipulation tools or archive utilities, where PHP's internal buffering might corrupt the output. It does not return any data, but it can provide the command's return status.

<?php
// Example: Using passthru to output a gzipped file directly to the browser
// This would typically be used with appropriate Content-Type headers.
// For demonstration, we'll use a simple 'echo' command.

// Create a dummy gzipped file for demonstration
file_put_contents('test.txt', 'This is some test content.');
exec('gzip test.txt');

$command = 'gunzip < test.txt.gz'; // Command to decompress and output
$return_var = 0;

echo "<pre>Output from gunzip via passthru():\n";
passthru($command, $return_var);
echo "</pre>";
echo "<p>Return status: {$return_var}</p>";

// Clean up dummy files
unlink('test.txt.gz');
unlink('test.txt'); // If gunzip created it
?>

Using passthru() to output the contents of a gzipped file.