Changing owner and group of newly created directories using PHP script

Wonder Works picture Wonder Works · Aug 13, 2014 · Viewed 10.2k times · Source

Dedicated Linux server running debain LAMP.

I run a PHP script (using a browser) which creates a directory (and various sub directories) in a folder on the same server for subsequent shared use using Dropbox.
The directories are created in /home/dropbox/New_Project_Name/new_folders and should be owned by the user 'dropbox'.

However running the php script causes the newly created directories generated by the script to be owned by 'www-data'

What is the best why of either running the php script from the browser so that it generates the new directories with ownership of user and group 'dropbox' or subsequently running a script to check for www-data ownership and recursively changing files and directories to 'dropbox'

Many thanks for any help.

Answer

DasSaffe picture DasSaffe · Aug 13, 2014

Not tested, but after creating the folder, you can run another line of code to change the owner/group

// define user and group
$owner = "dropbox";
$group = "dropbox";
$folder = "/home/dropbox/New_Project_Name/new_folders";

// change the owner and group
chown($folder, $owner);
chgrp($folder, $group);

Keep in mind, that it might throw an error, because there are subfolders and the operation fails. A while loop should solve the problem.

There might be an issues with the permissions, up to the server-config

There is another way to run it recursively with the "exec" command.

you can go like this:

exec("chown -R ".$owner.":".$group." ".$folder);

This will change user and group for the folder and all sub-folders. But beware, using system is "dangerous". You can run any shell-commands. Don't play around with it too much.