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
PHP Tutorial - 12 - Executing External Programs in PHP - System and Exec

You may also be interested in



About the Authors

Anto's editorial team loves the cloud as much as you! 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! Contact Anto Online if you want to contribute.

Support the Cause

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

Buy me a coffee



About Anto Online

Having started his career in 1999 as a Desktop Support Engineer, Anto soon changed paths and became a developer. After several years of development experience, he transitioned into a consultant. As an enterprise application consultant for a leading SaaS software provider, Anto specializes in AWS's serverless technologies. By day, Anto focuses on helping customers leverage the power of serverless technologies. By night, he indulges his passion for cloud computing by playing with Python and trying out things that are currently beyond the scope of his work. Sometimes Anto needs help as there are not enough hours at night. So Anto relies on a team of fellow Cloud enthusiasts to help him out. Each one is a Cloud expert in their own right, and Anto takes great pride in helping them learn and grow.

View all posts by Anto Online →

Leave a Reply

Your email address will not be published.