Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing owner and group of newly created directories using PHP script

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.

like image 393
Wonder Works Avatar asked Sep 02 '25 08:09

Wonder Works


2 Answers

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.

like image 190
Saffe Avatar answered Sep 04 '25 22:09

Saffe


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

like image 23
Wonder Works Avatar answered Sep 04 '25 22:09

Wonder Works