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 Anto

Hi, my name is Anto! I am a cloud computing hobbyist! Give me anything to do with the cloud, and I am interested. I work for a Cloud computing company by day and as a Cloud computing hobbyist by night! My projects use PHP, NodeJs, Ubuntu, MySQL and of course Amazon Web Services. Hopefully, my blog aids your cloud journey! Feel free to post a comment and share your thoughts.

View all posts by Anto →

Leave a Reply

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