(Urgent help required) run shell_exec() as root


I have lot of directories that have to be deleted automatically via a php script I’m running, but there are some files which have corrupt ownership etc. So PHP unlink or FTP delete is out of the question. Running the following in shell command-line does delete the directory and files inside it:

rm -r /home/cssexp/public_html/images/643553

However, I need to use it like the following, and there is no other way it should be done, I mean it has to be automated and run via php script:

shell_exec("rm -r /home/cssexp/public_html/images/643553");

The above works well for normal directories with normal ownerships, however for the other kind, root access is needed. I searched everywhere and if there were remotely any people who seemed to know how to get shell_exec to run as root, all they had to say was that it is dangerous and went on to provide examples of threats.

Please help me okay? I’m not concerned about security, no one else has access to the server except myself. It’s driving me crazy that there is no simple clear cut solution for me to get this over with.

I really find it odd that there is absolutely no information about this anywhere.

The best (and still somewhat secure) way is to create a script that just takes the number of the image to delete as a parameter, i.e.,

function isdigit()

        case $1 in
                *[!0-9]*|"") return 1;;
                          *) return 0;;

if isdigit $1
                rm -r /home/cssexp/public_html/images/$1

And now, armed with that script set up sudo so your user is allowed to run that script as root without asking for a password.
That way you can only run that script as root, and it will only work if the parameter you give it are all digits.
Can’t get it more (relatively, of course) secure than that I think.

Once that’s set up:

shell_exec("sudo /path/to/my/script 643553");

voila :slight_smile: