5

I get the output of a shell command in PHP as

$str = shell_exec("command");

and run the PHP script in terminal. When the shell command returns an error, it will be printed on the terminal. How can I tell shell_exec to return the command output only without any error output?

Googlebot
  • 15,159
  • 44
  • 133
  • 229

3 Answers3

7

You just have to discard error output by redirecting stderr to /dev/null

$str = shell_exec("command 2>/dev/null");

Non-error output - stdout - will be stored into $str as before.


Note that you don't need to suppress errors on shell_exec with the @ operator or wrap it into a try-catch block since shell_exec doesn't fail (you don't have a PHP runtime error).

It is the command it is asked to execute that may generate errors, the above approach will suppress those in the output.

Also some-command > /dev/null 2>&1 as other suggested is not what you want (if I understood correctly your question) since that would discard both error and non-error output.


A final note: you can decide to catch/discard stdout and/or stderr.

Of course you have to rely upon the fact that the command you're running send regular output to stdout and errors to stderr. If the command is not compliant to the standard (ex. sends everything to stdout) you're out of luck.

Paolo
  • 15,233
  • 27
  • 70
  • 91
0

If you want to ignore errors of your command, you need to modify your command to redirect errors like this:

some-command > /dev/null 2>&1
justyy
  • 5,831
  • 4
  • 40
  • 73
-2

You can do this too at the beginning of your code:

ini_set( 'display_errors', 0 );
error_reporting( E_ALL );

If you set 0, you won't see the errors, if you set 1 you will see all errors

nacho
  • 5,280
  • 2
  • 25
  • 34
  • Someone down-voted this but didn't say why. Reason is simple, as the author of the accepted response stated, shell_exec() is not really failing, you don't get a PHP run-time error even if the command executed inside fails. – Josafat Apr 11 '18 at 20:34