How to run PHP exec() as root?

I'm trying to build a firewall manager in PHP, but when I execute, <?php exec('iptables -L'); ?>, the result array is empty.

I have tried, <?php echo exec('whoami'); ?>, and the response is www-data (the user that Apache is using). What can I do to execute the exec function as root? (Preferably without changing the Apache user.)


Don't do it! You will leave yourself wide open to all sorts of malicious hackery.

Have a look at the "sudo" documentation.

You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.

As in:

exec ('sudo getIpTables.ksh')

You can run sudo through phpseclib, a pure PHP SSH implementation:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
$ssh->login('username', 'password');

$ssh->read('[prompt]');
$ssh->write("sudo command\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>