How To Run Basic Shell Commands From PHP

Today I will be showing you how to run basic shell commands from a PHP script. While you can’t interact with these commands (for example top will not output or update, you can still use them to somewhat interact with your web server. Note that most shared web hosting providers block these functions in their php.ini settings for security reasons. After showing how this works, I will also show you how to block these functions on your own web server.

There are 3 built in functions that will allow you to issue shell commands, each one is a little different in how it handles the commands given to it. I have linked to the php manuals for each function below if you are interested in learning more.

Running Shell Commands With shell_exec()

We will be using the shell_exec() to issue shell commands to our web server. You can substitute this function for any of the above if shell_exec is blocked although more than likely if one is blocked they all will be. I will begin by showing you the actual code and then breaking down how it works.


$cmd = "ls -a";

$returned = shell_exec($cmd);

echo "Command: $cmd:<br>";

echo "<pre>$returned</pre>"


So the first line of the above script will set our command ($cmd), then set the next variable ($returned) to run our command inside of the shell_exec() function. Then finally we echo what command was issued and the result that was returned. This will work for basic commands such as ls, rm, echo, etc. Any command that requires a response on the users end will more than likely not work due to how PHP works and the fact that you are unable to respond.

Blocking PHP Shell Commands On Your Server

Depending on what distribution or version of PHP you are using, your php.ini file may be in a different location. If you are unsure of where your php.ini file is located you can run the following command to find it. Note that you may have more than one result, you don’t need to worry about the “cli” php.ini.

find /etc -name "php.ini"

Once you have located your php.ini file, you need to modify the disable_functions setting and add exec, system, and shell_exec. If you are interested in blocking more functions, there is a nice little blog post about hardening your php.ini located here.

Last but not least, you need to restart your web server, you can do so by using one of the service commands depending on your distribution as follows.

service apache2 restart
service httpd restart

I hope this post has helped, please don’t forget to like, comment, or share. Thank you!

Leave a Reply

Protected with IP Blacklist CloudIP Blacklist Cloud