If you have a script that needs to access functions that can only be run as root (e.g. chmod, chgrp, mkdir, etc) you will find that you can’t call these directly since the Apache user is not root (at least it should not be root). There is no perfect solution around this as all solutions involve some security risk, but the least bad seems to be to use sudoer to grant root privileges to the script and then lock down the script so nobody other than root can modify the script.
First chmod the script so that anyone can execute it, but nobody other than root can modify it (I am assuming here that you are logged in as root, otherwise sudo).
chmod 111 /home/path_to_script
Next modify sudoer using visudo. It is a good idea to use visudo so that any change you make are updated without having to restart sudo.
Add the following line after the root entry in sudoer
apache_user ALL = NOPASSWD: /home/path_to_script
Change the apache_user to whatever your apache user is (e.g. nobody) and then add the path to your script. You might want to add your favorite editor (mine is nano) to your export in .bashrc. You should now be able to call your script from apache without problem.
Update. Make sure that you have commented out the
Defaults requiretty line in
visudo or else the script won’t be run by Apache. This problem wasted a couple of hours of my time since the script would run fine from the bash shell of the apache user, but not when called by apache. I finally took a look at the log file (yes I should have done this first) and there was the problem
sudo: sorry, you must have a tty to run sudo!