問題描述
如何使 644 個權限文件可從 PHP 寫入? (How do I make 644 permission files writable from PHP?)
我在 Apache Web 服務器上使用 PHP,但 PHP 缺乏寫入權限,無法創建新文件或修改現有文件,儘管需要修改的文件設置為通常的 644(和文件夾是 755)。
我的第一個猜測是問題在於 PHP 以不同於文件所有者的用戶身份運行,並且通過運行“posix_getpwuid(posix_geteuid());” 我發現 PHP 作為“www‑data”運行,而文件的所有者和組設置為“company123”。所以也許我應該簡單地將文件的所有者更改為“www‑data”?
但後來我決定檢查我一直在使用的其他一些 Web 服務器。在我嘗試的第一個中,使用 PHP 創建或修改 644 個文件沒有問題,但是所有者和組被命名為“600”,而 PHP 作為用戶“wse253421”運行。顯然,PHP 可以作為一個用戶運行,並寫入另一個用戶擁有的 644 個文件。它是如何工作的?
這是怎麼回事,我應該如何處理 PHP 在第一台服務器上缺乏寫權限?
參考解法
方法 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
(by omanaga、QuantumTiger)