Linux – Remove files with PHP owned by different user

apache-2.2linuxPHP

I have a PHP-script in which I'm trying to unlink files from a directory. The files in this particular directory have been uploaded using FTP under a different account than the one Apache is running under.

PHP runs on the server using mod_php, so I assume PHP scripts are executed as the same user Apache is running as. Probably because of this, the unlink fails.

I am running Apache 2.2.3 with PHP 5.1.6 on CentOS. Most of this is administered by Plesk 8. I do have full access to the shell though.

I have tried to create a new group in which I put the FTP user and the Apache user. I then changed the GID of the files to that new group so that PHP should be able to unlink the files. No success.

I have read about options like suPHP en suEXEC, but my knowledge of those products is limited.

What would be the best way to be able to remove those files using a PHP script?

Best Answer

When I have to things from PHP that require root privileges on a system that has mod_php I usually write a small helper script to actually do the task. Then I use system() or proc_open() to call the script via sudo. You will need to configure your apache user account to be able to run that particular script with no password.

If the system has the cli version of php installed then you can write your helper script in PHP since it sounds like that is familiar to you.

/etc/sudoers looks like this:

Cmnd_Alias PHPHELPER=/path/helper-script 
www-data ALL=NOPASSWD: PHPHELPER

The advantage of doing this is that you can write a very tight and specific helper script that only performs one task, and you can add lots of good error checking to prevent badness. This minimizes the potential for a system compromise.