How to view shell_exec() errors in PHP

Let’s say you execute shell commands via a PHP script using the shell_exec() method, but you do not see any error messages related to the executed shell command.

This behavior can be changed by adding “ 2>&1 ” to your shell command. The additional characters inform the shell to pipe all responses back to the shell_exec() method.

This behavior by the shell_exec() method is expected because the response string can be NULL when an error occurs or if the command produces no output. The PHP exec() method should be used when access to the program exit code is required.

Examples:

<?php
echo shell_exec("mkdir /mnt/efs/test");
?>

Will result in no response.

<?php
echo shell_exec("mkdir /mnt/efs/test 2>&1");
?>

Will result in:

mkdir: cannot create directory '/mnt/efs/test': Permission denied

Read my article How to execute shell commands via PHP for more information on the PHP exec() and other methods.

 

 



About the Authors

Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic!

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



Leave a Reply

Your email address will not be published. Required fields are marked *