使用PHP脚本更改新创建目录的所有者和组

4

运行debain LAMP的专用Linux服务器。

我使用浏览器运行PHP脚本,该脚本在同一台服务器上创建一个目录(及各种子目录),以便通过Dropbox进行共享使用。
这些目录将被创建在/home/dropbox/New_Project_Name/new_folders中,并应由用户'dropbox'拥有。

然而,运行php脚本会导致由脚本生成的新建目录的所有权归属于'www-data'

最好的方法是通过浏览器运行php脚本,使其生成带有用户和组“dropbox”的新目录,或者随后运行脚本来检查www-data所有权并递归更改文件和目录为“dropbox”

非常感谢您的任何帮助。

3个回答

4

未经测试,但在创建文件夹后,您可以运行另一行代码来更改所有者/组

// 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.


非常感谢 - 但我收到了“操作不允许”的错误提示,我猜是由于服务器权限的问题。答案中的第一个变量应该是$user而不是$username。 - Wonder Works
是的,你说得对。我编辑了变量并提出了另一种解决方法。 - DasSaffe
好的 - 我正在尝试使用您展示的exec选项,但是在尝试理解如何赋予脚本运行权限。我已将以下一行添加到/etc/sudoers的底部。code nobody ALL = NOPASSWD: /home/user/public_html/change_owner.php - Wonder Works
好的 - 终于把这个搞定了(谢谢大家),但是我将以下内容添加到我的 /etc/sudoers 中 `www-data ALL=(ALL) NOPASSWD: /bin/chown, /home/sites/public_html/change_owner.php' PHP 文件的内容与 DasSaffe 的答案一样。 - Wonder Works
chown($folder, $owner); - 根据http://php.net/manual/ru/function.chown.php,仅适用于文件。 - Sasha Kos

1

好的 - 最终让这个工作了(谢谢大家),但是需要将以下内容添加到我的/etc/sudoers

www-data ALL=(ALL) NOPASSWD: /bin/chown, /home/sites/public_html/change_owner.php

PHP文件的内容与DasSaffe的答案中所述相同。

0

这里有三个选项:

  1. 使用suEXEC。
  2. 作为用户dropbox连接到本地ftp,并以此方式创建目录和文件。
  3. 设置sudo,使得www-data用户可以作为root执行此操作而无需密码提示:sudo chown -R dropbox /path/to/dir,然后只需使用php的exec函数即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接