Executing root commands from PHP...Is there a safe way?

command, php, root

Solution

Write specific scripts that can be run as root and use the setuid bit to do it, so that Apache can run just those scripts as root. IE

#! /usr/bin/php (or wherever your php binary is)
<?php
   // Some PHP code that takes in very limited user input,
   // validates it carefully, and does a sequence of actions
   // that you need to run as root.

   // This could easily be a shell script (or whatever else you want)
   // instead of PHP. That might be preferable in many situations.
?>

Then make sure that that script is owned by root and group'd by your user that Apache runs as:

chown root:www-data myscript.php

Then make it run as owner:

chmod u+s myscript.php

And make sure that Apache can execute it:

chmod g+x myscript.php

Problem

I was thinking about to make a little web-based Linux control panel (just for fun). First potential problem that came to my mind is that i would need to give Apache's user root-level permissions to run those commands, which would compromise the security of the whole system. Installing a dedicated web server for the system is not really an option. Maybe I could run a 2nd Apache instance (keeping the 1st one for regular users) but not even sure if possible. So, what you guys think? What are my best options here? Thanks in advance for any input. EDIT: Ok guys thanks for all the suggestions, i'll keep them in mind.

Original source