Changing owner and group of newly created directories using PHP script
Solution 1
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.
Solution 2
OK - finally got this working (thanks everybody) but adding the following to my /etc/sudoers
www-data ALL=(ALL) NOPASSWD: /bin/chown, /home/sites/public_html/change_owner.php
The contents of the PHP file were as in the answer from DasSaffe
Wonder Works
Updated on June 27, 2022Comments
-
Wonder Works almost 2 years
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.
-
Wonder Works over 9 yearsMany thanks - but I get 'Operation not permitted' I guess due to server permissions. First variable in the answer should be $user and not $username.
-
DasSaffe over 9 yearsYep, you are right. i edited variables and gave another approach to solve it
-
Wonder Works over 9 yearsOK - I'm trying with the exec option as you show, but trying to understand how I can give the script permission to run like this. I have added this line to bottom of /etc/sudoers.
code
nobody ALL = NOPASSWD: /home/user/public_html/change_owner.php -
Wonder Works over 9 yearsOK - finally got this working (thanks everybody) but adding the following to my /etc/sudoers `www-data ALL=(ALL) NOPASSWD: /bin/chown, /home/sites/public_html/change_owner.php' The contents of the PHP file were as in the answer from DasSaffe
-
Sasha Kos almost 6 yearschown($folder, $owner); - according to php.net/manual/ru/function.chown.php only for files