当 运行 作为 root 时,如何让 PHP 创建具有特定组的文件?

When running as root, how can I make PHP create files with a specific group?

我有一个 PHP 脚本,它 运行 是根用户。该脚本会创建一些文件,这些文件应该属于指定的用户和组。我已经设法让脚本创建具有正确所有者的文件,但是,与文件关联的组仍然是 root.

这是我正在做的事情的概念验证:

$userInfo = posix_getpwnam('eric');
posix_initgroups($userInfo['name'], $userInfo['gid']);
posix_setuid($userInfo['uid']);

file_put_contents('test.txt', 'Some content');

然后我运行它作为root:

sudo php test.php

它创建一个绑定到根组的文件:

Access: (0644/-rw-r--r--)  Uid: ( 1000/    eric)   Gid: (    0/    root)

如何强制 PHP 使用正确的 Gid 创建文件?

旁注:脚本需要能够 运行 作为 root,并且 运行 su - $user 在我的场景中不是一个选项。

设置 UID 后将 posix_setgid($userInfo['gid']); 添加到脚本中应该可以解决问题。

你可以使用 chgrp() after the fact or try the same posix methodology but with the group: posix_setgid().

The appropriate order of function calls is posix_setgid() first, posix_setuid() last.