Our highest priority is to satisfy the customer through early and continuous delivery of valuable and working software.

Wednesday, May 9, 2007

How to capture error in php if exec() function fails to run some command

How to capture error in PHP if exec() function fails to run some command?

e.g. $command = "ls";
exec($command, $output, $return_value); will give
$return_value = 0 & $output contains list of files.

but if $command = "lk";
In this case error will be "lk: command not found"
But exec() command will not capture error into $output.

So, use this before calling exec() function.
$command .= " 2>&1";

It will redirect the STDERR stream to STDOUT, so that you can capture both OUTPUT as well as ERROR from your PHP script into $output.


  1. tell me about it.

    amazing, you made this post in 2007, and still, 2 years later, no one has an asnwer ?

  2. I have the same issue today...

    ssh'ing to a host bails because the host key doesn't match known_hosts.

  3. exec('echo $((command here) 2>&1)', $output, $return_value); works like a charm