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.

 

 

Leave a Reply

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