How to retrieve PHP exec() error responses?

How to retrieve PHP exec() error responses?

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

Stefan Bogdanescu

Founder & Senior Architect

The Silent Failure of exec() and How to Actually See Errors

Using exec() in PHP to run system commands is a common pattern for automation tasks, like creating symbolic links or clearing logs. However, exec() has a default behavior that often confuses developers: it discards the standard error output of child processes unless you explicitly tell it otherwise. In your specific case, running a ln -s command failed due to permissions issues on the target server, yet the script continued as if nothing happened. Adding an or die() block only tells you that the command returned a non-zero exit code, not why it failed.

To diagnose this, you need to capture both the return status and the actual error message printed to stderr by the shell. The solution involves modifying how you invoke the command or capturing the output streams directly.

Capturing Standard Error with exec()

The most direct fix is to tell exec() to capture the standard error stream. By default, exec() runs the command and discards any errors sent to stderr. You can change this by appending a third parameter to the function call, which will store the combined output (stdout + stderr) into a variable.

Here is how you should structure that specific line:

$output = exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1');
$exitCode = exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess > /dev/null 2>&1', $output, $returnVar);

if ($returnVar !== 0) {
    // At this point, $output contains the error message from the shell
    echo "Command failed with exit code {$returnVar}. Error: {$output}";
}

However, using exec() twice (once to get output, once for the return code) is inefficient and prone to race conditions if the command modifies files between calls. A cleaner approach is to use a single call where you pass an array to capture both streams separately, or simply rely on the third parameter of exec() to grab everything from stderr.

The most reliable pattern using exec() for error logging looks like this:

$output = [];
$returnCode = 0;
$errorMessage = exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1', $output, $returnCode);

if ($returnCode !== 0) {
    // $errorMessage will contain the raw stderr output
    error_log("Symbolic link creation failed: " . $errorMessage);
}

Note that exec() returns only the last line of output when a string is passed as the second argument, but if you pass an array (as shown), it captures all lines. The third parameter, $returnCode, holds the exit code. If the command fails due to permissions, the shell will typically print a message like ln: failed to create symlink ... Permission denied to stderr, which gets captured in $errorMessage.

Using shell_exec() for Simpler Error Handling

If you don't strictly need the ability to execute multiple commands or manage complex streams, shell_exec() is often easier to work with because it returns the entire output of the command as a string. To capture errors, you must redirect stderr to stdout within the command string using 2>&1.

$result = shell_exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1');

if ($result === false) {
    // This happens if the process fails entirely or is killed by SIGHUP
    error_log("Process failed silently: " . $result);
} else {
    // Check for non-zero exit codes in the output if possible, 
    // though this requires parsing the command's internal logic.
    // Better to check return status via system() if available.
}

While shell_exec() is convenient, it still doesn't give you a direct integer return code without parsing the output or using additional tools. For strict error handling, checking $returnCode from exec() is generally preferred.

Consider system() or proc_open() for Robustness

Another alternative is system(), which behaves similarly to shell_exec() but provides a boolean return value indicating success or failure based on the exit code. However, like exec(), it does not return the actual output unless you capture it via a third parameter (in newer PHP versions) or by redirecting output in the command string.

$success = system('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1', $status);

if ($status !== 0) {
    // The output is not directly available here without additional logic
    // You might need to pipe it through a temp file or use proc_open
}

For complex scenarios where you need full control over stdin, stdout, and stderr, proc_open() is the most powerful option. It allows you to set up pipes for each stream separately, ensuring that permission errors are never lost. However, this adds significant complexity and overhead compared to simple exec() calls.

Why Permissions Errors Are Silent by Default

In your original example, the command failed because PHP lacked write permissions in /. When a shell command fails due to permissions, it prints an error message to stderr, not stdout. Since exec() discards stderr by default, the error message vanishes. The or die() pattern only triggers if the exit code is non-zero, but without capturing stderr, you are left with no context about the failure reason.

To resolve this permanently, ensure your web server user (e.g., www-data or apache) has the necessary permissions to create symbolic links in the target directory. Alternatively, run the script via a CLI user with elevated privileges if automation is the goal. But for debugging, always remember: redirect stderr to stdout (2>&1) and capture the return value to see what went wrong.

Our network