PHP exec() vs system() vs passthru()

PHP exec() vs system() vs passthru()

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP exec() vs system() vs passthru()

When you need to invoke an external command from PHP, the standard library offers three distinct functions: exec(), system(), and passthru(). While their signatures look identical—accepting a string of code and optionally capturing output—their behaviors diverge significantly in how they handle streams, return values, and error reporting. Choosing the right one isn't just about syntax; it dictates how your application handles binary data, timing, and shell errors.

Capturing Output vs. Streaming

The primary distinction lies in how these functions interact with the output stream and the return value of the executed command.

exec() is designed for capturing output into a variable and retrieving the exit status separately. When you call exec('ls', $output), it buffers the entire standard output and standard error into the $output array (where each element corresponds to a line). Crucially, exec() suppresses direct output to the browser or console; everything goes into memory until you print $output. This makes it ideal for parsing text results or checking if a command succeeded. For example:

$command = 'whoami';
$output = [];
$return_var = 0;
exec($command, $output, $return_var);

if ($return_var === 0) {
    echo "Success: " . implode("\n", $output);
}

However, this buffering behavior can be a bottleneck. If you are piping large amounts of data or dealing with binary files, storing the entire stream in an array consumes unnecessary memory. exec() also appends a newline character to each line in the output array, which you must manually trim if precision matters.

Direct Output and Shell Errors

system() behaves similarly to exec() regarding buffering, but it adds a critical feature: it flushes the output stream directly to the client (or console) before returning. This means the command's output appears in the browser immediately as it is generated by the external process. Furthermore, system() returns the full exit code of the last line of output, which can sometimes be ambiguous if the command outputs multiple lines.

If you need to inspect the raw output while still seeing it on the screen, system() is your choice. However, because it buffers internally before flushing, very large outputs can still cause memory spikes. A common pitfall with system() is that it does not provide an easy way to capture the exit status of the last line cleanly if the command produces verbose output; often you have to parse the final line manually or rely on exec() for strict error checking.

$command = 'ls -la';
system($command); // Output is printed directly, return value is the last line's exit code

Streaming Binary Data

passthru() is the specific tool for handling binary data or massive streams. Unlike exec() and system(), which buffer their output internally, passthru() writes directly to the output stream without buffering. This prevents memory exhaustion when processing large files or streaming data from a remote server. Additionally, passthru() allows you to pass a second argument to capture the exit code of the command while still streaming the output.

This function is essential for tasks like downloading large files, piping compressed archives, or serving video streams. Note that passthru() does not return the output; it only returns the exit status code (or false on failure). Attempting to use passthru() for text parsing is usually an anti-pattern because you lose the ability to easily manipulate the data in memory before displaying it.

$command = 'tar -czf /tmp/archive.tar.gz /var/www';
passthru($command); // Streams output directly, no buffering

Security Considerations

Regardless of which function you choose, passing user input directly into these commands is a severe security vulnerability. PHP will not escape quotes or special characters automatically. If a user inputs ; rm -rf / into a variable passed to any of these functions, the shell executes that malicious command. You must always sanitize input using strict whitelist validation or escaping mechanisms (like escapeshellarg()) before execution.

Recommendation

If you are running a script like Bash or Python:

  1. Use exec() if you need to parse the output, check specific exit codes, and don't care about immediate streaming.
  2. Use system() if you want to see the command's progress in real-time but still need some level of buffering control.
  3. Use passthru() exclusively for binary data, large file transfers, or when memory efficiency is critical.

Avoid using shell_exec(), as it behaves like exec() but returns a single string rather than an array, making line-by-line processing slightly more cumbersome. Always prioritize passthru() for performance-critical streaming tasks and remember that none of these functions replace the safety of properly escaping shell arguments.

Our network