views:

580

answers:

5

I have a PHP script which changes file permissions on my server using chmod. I'd like to be able to run the script both via the browser (as nobody) and via a cron job (as username).

Is it correct that only the owner of the file can change the permissions? I.e. if I create a file via a cron job and set the permissions, I can't then change those permissions when running the script from the browser?

Are there any ways round this please? Delete (unlink) and re-create the file as whatever user the script is running as? Or is there a way of running a php script via a cron job as nobody? / via the browser as username?

The aim is to be able to make images publicly viewable or not by changing the file permissions.

A: 

Usually only the owner or the super-user (or equivalent)

Matthew Flaschen
A: 

Only the owner of the file can do this, I would recommend running the cronjob as 'nobody' instead.

Evert
+1  A: 

You can do this without putting a username or password in your script.

In your crontab have sudo execute the script as the user that your web server runs as. Following your example, I'll use the nobody user.

0 12 * * * (sudo -u nobody php ./yourscript.php)

Note that the "nobody" user (as well as users like "apache") do not normally have login privileges. This may require you to allow sudo to execute scripts without a tty. You'll know this if you receive an error like: "sudo: sorry, you must have a tty to run sudo"

Allowing this can be done by commenting out the "Defaults requiretty" line using the visudo command. As with any change to sudo, you may want to search for any side-effects this change may come with.

RC
+1  A: 

Solution 1: Create a group for both the user and the cron user, add each user to your new group, and give both users access to read and write to the file (chmod g+rw filename). (safer then the next solution).

Solution 2: The simplest way to do this is to make the file readable and writable by everybody (chmod a+rw filename) would have this effect.

I would not recommend this for production usage though.

deepwell
A: 

Yes, only the owner of the file can do this. Your options depend on what kind of control you have over the server.

If you have enough control over the server, you can use SuPHP instead of Apache's mod_php. That way, the PHP scripts will be run as the user who owns the script, and any files created by a PHP script will be owned by the same user.

If you don't have that much control (common shared web hosting, for example), you could use something like Joomla's FTP approach. When FTP support is turned on in Joomla, it does all file manipulation using FTP. That way, it can create or manipulate files with the same permissions as the FTP user.

Something like this (error handling ommitted):

$ftp = ftp_connect('localhost');
ftp_login($ftp, 'username', 'password');
ftp_chdir($ftp, '/root/to/website');
ftp_chmod($ftp, 0644, 'filename.ext');
ftp_close($ftp);
BlackAura