How to use chown command in PHP?
I want the user to be able to read and edit files in the test folder, these files are always created by a software with read-only properties.
I can't use the chown command manually, so I need a chown command that can work in PHP before the user's read and write commands automatically.
Manual ok:
root@vultr: chown -R nginx /var/www/html/test //run ok, All files in the test folder can be read and written
root@vultr:~# /var/www/html/test/test.sh //run ok, the test.sh file contains the "chown -R nginx command /var/www/html/test"
My php code but not working
shell_exec('./test.sh');
chown('file_webuser', 'nginx');
Solution 1:
The chown (change owner) won't work for non-root user. What you really need to do is to grant the user (I assume it's a nginx
) full permissions to files.
It can be achieved in few ways. The most secure way is to run PHP (I'm guessing PHP is running as a PHP-FPM) as a nginx
user by editing params user
and group
in your php-fpm.conf
file and restarting the PHP service.
In such case, the owner of files will be the same, so no file permission manipulation is needed. You'll need to change ownership of all files generated/uploaded by PHP to nginx once (using root user and chown command).
The second solution is to add the user who's running PHP-FPM to the same group as the nginx user and modify umask
so the files are accessible to a group. Let's say that the group would be www-data
(you have to add nginx
user and the PHP-FPM process owner to that group, for example with usermod
command, and edit your php-fpm.conf
: set group
to www-data
). Then in your PHP scripts use umask
function to allow all members of group to have full access to files: umask(0007);
.
The third, least secure way is to give full access to your files for all users in the system. Use umask
function in your PHP file to achieve this: umask(0000);