How to find php exec() function run without error

Use the following method to trace exec() function in PHP.

Syntax:

[php]
exec($command, $output, $return_value);
[/php]

example1:
[php]
$command = "ls";
exec($command, $output, $return_value);
// $output will contains list of files as array.
// $return_value will be zero.
[/php]

Output:
Array
(
[0] => File1.txt
[1] => File2.txt
)
0

example2:
[php]
$command = "l2";
exec($command, $output, $return_value);
// "l2: not found" this error will araise if use the above command
// So, exec() command will not capture error into $output.
// $return_value will be not zero.
[/php]

So, we can 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.

example3:
[php]
$command = "l2";
$command .= " 2>&1";
exec($command, $output, $return_value);
[/php]

Output:
Array
(
[0] => sh: 1: l2: not found
)
127

Permanent link to this article: https://blog.openshell.in/2012/11/how-to-find-php-exec-function-run-without-error/

Leave a Reply

Your email address will not be published.