Why does file_put_contents have permission issues

2019-08-07 06:31发布

This question has been asked a couple of times up here, but I haven't found a solution yet. I have a Fedora 19 LAMP server and I just want to run the simple command: file_put_contents('test.txt', 'Hello there'); in order to confirm that my web server can use PHP to write data to files. I'm having trouble figuring out a proper permissions scheme. To start, just for development, Apache's document root is /var/www/html. This directory was originally owned by a user and group called www-data, but I changed the directory's group to the primary group of the owner of the httpd process, named apache. It is this owner that is active when PHP runs. I've confirmed this with the following:

enter image description here

As you see, the process owner is apache, the current direcory is /var/www/html/php-console. The directory is owned by www-data and members of the group apache have full access to it.

I have tried the following to get PHP to actually create a file in this location, but to no avail:

chmod 777 /var/www/html/php-console

chown apache /var/www/html/php-console
chgrp apache /var/www/html/php-console

cd /var/www/html; > test.txt; chmod 777 test.txt;

Nothing will work while this script is run from the browser. However, when I use file_put_contents with the PHP CLI, it works just like I would expect, provided that the user I'm entering commands as or its group has write permissions to this directory or test file.

enter image description here

So, from the command line, you see how www-data has read, write, and execute permissions to the folder I'm in. posix_getpwuid and posix_geteuid help you to find the owner of the Apache/PHP process, which in this case is the same as the user logged into the console. file_put_contents succesfully writes 8 bytes to the specified file. If I change the group or owner and group to something else, I get Permission denied, which absolutely makes sense.

If this works on the command line, then why not when I really want it to, i.e., while actually serving web pages???

1条回答
Animai°情兽
2楼-- · 2019-08-07 07:25

Because you forgot to read the httpd_selinux(8) man page and give the directory the appropriate file context to allow the web server to write files there.

查看更多
登录 后发表回答