How to view shell_exec() errors in PHP

Photo by Anete Lusina on Pexels
Published 22 June 2018 Last updated 17 June 2022 An older guide that hasn't been re-checked yet, so commands or versions may have moved on. How guides are made and checked

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
Watch the video on YouTube

You may also be interested in