PHP: Why isn't exec() returning output?
When invoking system commands from PHP, it is tempting to assume that exec() acts as a universal capture mechanism for everything the underlying process writes to stdout and stderr. A common scenario involves checking network connectivity using the Linux ping command. If you run a script where $domain_bad = "lksjdflksjdf.com" and execute exec("ping -c 1 $domain_bad", $output, $return_var), you might expect to see the error message "ping: unknown host lksjdflksjdf.com" inside the $output array. However, when that specific error occurs, $output remains empty, even though $return_var correctly reflects the non-zero exit code (e.g., 2).
This behavior stems from how child processes manage standard streams and how PHP captures them by default. When you call exec(), PHP redirects the child process's standard output (stdout) and merges it into a single array that gets stored in $output. However, this capture mechanism has a critical limitation regarding error streams. By default, the child process writes its error messages to standard error (stderr), not standard output (stdout). When ping detects an unknown host, it writes the diagnosis message directly to stderr. Because PHP's exec() does not automatically merge stderr into the $output array unless explicitly configured, that text is effectively discarded from your PHP variable, even though the process terminates with an error code.
You can verify this behavior by observing what happens with a successful command versus a failed one. When pinging a valid domain like yahoo.com, ping successfully resolves the address and outputs IP information to stdout. In this case, $output contains the expected lines. Conversely, when the host is unreachable or unknown, the message goes to stderr, leaving $output empty while $return_var signals the failure.
To retrieve that error message within PHP, you must explicitly tell the shell or the command how to handle streams. The most direct approach is to redirect stderr into stdout using shell syntax before passing the string to exec(). By adding 2>&1 to your command line argument list, you instruct the shell to merge file descriptor 2 (stderr) into file descriptor 1 (stdout).
<?php
$domain_bad = "lksjdflksjdf.com";
// Redirect stderr to stdout so exec() can capture it.
exec("ping -c 1 $domain_bad 2>&1", $output, $return_var);
var_dump($return_var); // int(2)
echo "return_var is: $return_var" . "\n";
var_dump($output);
// Now outputs the error message in the first element of the array.
// string(37) "ping: unknown host lksjdflksjdf.com\n"
?>
In this revised example, the $output array now correctly contains the error string because the shell successfully redirected the stream before PHP attempted to capture it. This technique is essential for any scenario where you rely on exit codes alone to determine success but still need diagnostic text from the command itself.
There are trade-offs to consider when choosing between exec(), system(), and shell_exec(). All three functions share similar limitations regarding stream redirection unless you apply shell syntax like 2>&1. If you prefer not to rely on shell interpretation, using the proc_open() function offers more granular control over file descriptors. With proc_open(), you can define an associative array that explicitly maps standard error to a specific stream wrapper or merges it into stdout at the process level, rather than relying on shell syntax. While shell_exec() is often simpler for quick scripts, remember that it also requires the 2>&1 trick to capture stderr in a single string, as it does not separate streams like proc_open() can.
Another important pitfall involves variable expansion and injection risks. In the example above, injecting $domain_bad directly into the command string relies on shell parsing. If the domain name contains characters that could be interpreted as shell operators (such as pipes or quotes), you risk command injection vulnerabilities. Always quote your arguments carefully or pass them as an array to exec():
<?php
$domain_bad = "lksjdflksjdf.com";
// Passing as an array prevents word splitting and injection issues.
exec("ping -c 1 $domain_bad 2>&1", $output, $return_var);
?>
When building robust infrastructure scripts, relying on $return_var is often sufficient for logic flow, but capturing the stderr output via stream redirection ensures you don't lose valuable debugging information when things go wrong.
