I'm using PHP function shell_exec()
to execute Shell Script. When I use this(correct) syntax, it displays output normally
echo shell_exec("ls -l");
But, for some reason, if user enters invalid command like this
echo shell_exec("lsl -l");
by default, it should give error as it gives on terminal. But, it doesn't display anything. is there any way to catch and display errors as well; via PHP?
That's because the output of the error goes to STDERR
, while shell_exec
only reads STDOUT
. The simplest solution would probably be to pipe STDERR
to STDOUT
:
<?php
echo shell_exec('lsl -l 2>&1');
If you only want to know if the command was successful, I would use exec rather than shell_exec, as you can get the return value.
From the PHP docs:
This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.
If you choose to use exec() instead, you can supply a third param to the function which will return the output of the arguments:
exec ( string $command [, array &$output [, int &$return_var ]] )
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.