How do I make 644 permission files writable from P

2019-08-12 18:59发布

问题:

I'm using PHP on an Apache web server, but PHP lacks write permission and can't create new files, or modify existing ones, despite that the file that needs to be modified is set to the usual 644 (and folders are 755).

My first guess was that the problem was PHP running as a different user than the file owner, and by running "posix_getpwuid(posix_geteuid());" I found that PHP ran as "www-data", while the file had owner and group set to "company123". So maybe I should simply change the owner of the file to "www-data"?

But then I decided to check some other web servers I've been working with. On the first one I tried, I had no problems creating or modifying 644 files with PHP, and yet, the owner and group were named "600", while PHP ran as the user "wse253421". So apparently, it's ok for PHP to run as one user, and write to 644 files owned by another user. How does that work?

What's going on here, and what should I do about PHP lacking write permission on the first server?

回答1:

644 is Read/Write permission to the owner and read-only permission to the group and the world. So if the file is not owned by the same user as the web server runs under, PHP will not be able to write to it, regardless of the group. If (as you say) it seems to be doing this then the web-server user is an alias of the file owner, ie they share the same uid.

For group write the file needs to be 664 and the group needs to be the same as the group that the webserver runs as (often www-data but not guaranteed!). If the file belongs to a different group, 664 won't help. 666 would, but is not recommended since that allows anyone to write to the file.

To create new files the permissions on the directory are the important factor. 755 is Read/Write/Execute for the owner and Read/Execute for group and world. If you want group write you need 775 and again the group needs to be the same group as the webserver runs under.

Edit: If you need to check the webserver user/group temporarily chmod the directory to 777 and have it write a file. Then check the file owner and group. Just don't forget to chmod it back to a more secure setting

The best solution for your first server would probably be to chgrp the files and directories you need to write to, to the group of your webserver (probably www-data), chmod the files to 664 and chmod the directories to 775

See https://www.ics.uci.edu/computing/linux/file-security.php

See also answer by Thomas Rutter here: https://askubuntu.com/questions/386928/default-permissions-for-var-www