I have a PHP script which runs as root. The script creates some files, and those files should be owned by a specified user and group. I have managed to make the script create the files with the correct owner, however, the group associated with the files is still root
.
Here's a proof-of-concept for what I'm doing:
$userInfo = posix_getpwnam('eric');
posix_initgroups($userInfo['name'], $userInfo['gid']);
posix_setuid($userInfo['uid']);
file_put_contents('test.txt', 'Some content');
Then I run it as root:
sudo php test.php
It creates a file that is tied to the root group:
Access: (0644/-rw-r--r--) Uid: ( 1000/ eric) Gid: ( 0/ root)
How can I force PHP to create files with the correct Gid
?
Side note: The script needs to be able to run as root, and running with su - $user
is not an option in my scenario.
You could use 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.