Home » Php » shell – How to retrieve PHP exec() error responses?

shell – How to retrieve PHP exec() error responses?

Posted by: admin April 23, 2020 Leave a comment


Below is the command I tried executing, without success:

exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess');

When you add a die() at the end, it catches that there’s an error:

exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess') or die('what?!');

For the above exec() statement, a permissions problem is causing the error, but PHP isn’t displaying it. How do you display from PHP what error is occurring?

How to&Answers:

You can receive the output result of the exec function by passing an optional second parameter:

exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess',$output);


The $output parameter does not appear to work if the calling program spits output to STDERR.

A better way to handle this is to redirect the output from exec to a file and then display the contents of that file if there is an error condition.

If $cmd holds the exec command add something like this:

$cmd.=" > $error_log 2>&1"

Then examine the contents of the filespec in $error_log for detailed info on why the command failed.

Also note that if you fork this off with a & at the end of the command, an immediate check of the contents of $error_log may not reveal the log information – the script may check/process the file before the OS has finished.


The following code will capture both the normal output (from StdOut) and the error output (from SdtErr).

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


This worked for me in several scenarios:

 exec($cmd . " 2>&1", $output);
 $result = ob_get_contents();

The space between ” 2 is important


this worked for me:
Append 2>&1 to the end of your command.

Seen here:
php exec() not returning error message in output when executing svn command



If you don’t find the error through that second parameter, you can search for the error log of apache, for example in Ubuntu Server 12.10 through the command
$ tail /var/log/apache2/error.log
I was running a python script from php, whose error was only printed there, and hence I was able to diagnose it.
Best regards.


This in not a direct answer to your question, but is very useful, if you want to know what exactly happened by returned error code.

If error code ($res), returned by command:

exec('command', $out, $res);

was in range 1-2, 126-165, 255, than it was returned by shell (eg. BASH) invoked from PHP (to execute your command). If returned code is not in this range, than it was returned by your command (not shell).

See (for BASH error code descriptions)