Unix Websites

Running root commands in PHP via Apache

I have a web application that needs to perform shells commands as root within a PHP function, and you would think that would be pretty straight forward… but it did take my a few googles to get all the details, so here are my handy notes on it. This is on a Linux system running Apache, and we’ll be using “sudo” within “shell_exec” to run the commands.

The main thing is to edit the /etc/sudoers file, and typically you can (as root) use the ”visudo” command to do so.

Make sure apache can run commands, AND not require a password:

apache  ALL=(ALL)       NOPASSWD: ALL

Then you need to comment out this line:

#Defaults    requiretty

If you don’t, then you will see these errors in /var/log/secure: “sorry, you must have a tty to run sudo”. Now you are ready to go, and the PHP code is simple:

$results = shell_exec(‘sudo date’);