Many a times we need to execute system commands on a Linux system – to delete a directory, or restart a service. However, since Apache does not run with root privileges, it is nearly impossible to use PHP’s exec(), system() or passthru() functions to achieve that.
The solution to this is very simple, specially on Ubuntu. The Apache’s user www-data need to be granted privileges to execute certain applications using sudo.
1. Run the command sudo visudo
2. At the end of the file, add the following
www-data ALL=NOPASSWD: /sbin/iptables, /usr/bin/du
This is assuming that you wish to run iptables and du using super user (root) privileges. However, if you wish to run every application using super user privileges, then add the following instead of what’s above
www-data ALL=NOPASSWD: ALL
3. That’s it, now use exec() in the following manner inside your .php script
exec ("sudo iptables -P FORWARD ACCEPT");
This has enabled me to execute scripts on my server for which I had to earlier use setuid and combination of cron and what not. But now, it’s as convenient from within PHP.