Difference Between shell_exec and system in PHP

When executing terminal commands in PHP, developers often choose between the shell_exec() and system() functions. While both functions allow you to run system-level commands directly from your PHP script, they handle output, return values, and buffer flushing differently. This article explains the key functional differences between shell_exec() and system() to help you choose the right tool for your application.

The shell_exec() Function

The shell_exec() function executes a command via the shell and returns the complete output as a string.

Key Characteristics of shell_exec():

Example:

$output = shell_exec('ls -la');
// The output is stored in the variable; nothing is printed yet.
echo "<pre>$output</pre>";

The system() Function

The system() function executes a command, immediately flushes the output to the browser or output buffer, and returns only the last line of the command’s output.

Key Characteristics of system():

Example:

// This will immediately print the directory listing to the browser
$last_line = system('ls -la', $retval);

// You can check if the command executed successfully (0 usually means success)
echo "Last line of the output: " . $last_line;
echo "Return value of the command: " . $retval;

Comparison Summary

Feature shell_exec() system()
Primary Purpose Capturing full command output for processing. Executing a command and displaying output in real-time.
Output Behavior Returns output silently; does not print to screen. Prints output directly to the browser/terminal.
Return Value The entire output of the command as a string. Only the last line of the command output.
Status Code Capture No built-in parameter to capture exit status. Yes, via the optional second parameter &$result_code.

Which One Should You Use?