关于php:fopen():无法打开流:权限被拒绝(路径权限为777时)

fopen(): failed to open stream: Permission denied (when path permission is 777)

本问题已经有最佳答案,请猛点这里访问。

[Duplicated]

当所有路径都具有777许可权时,PHP函数fopen()获得许可权错误。
服务器详细信息:Centos 7 , PHP 7.1.8 , Apache 2.4.27

PHP源代码:

1
$myfile = fopen("newfile.txt","w") or die("Unable to open file!");

错误信息 :

Warning: fopen(newfile.txt): failed to open stream: Permission denied in /var/www/html/test/file.php on line 3

MyTest网址:http://MyIPAddress/test/file.php

777个许可路径:

1
2
3
4
/var/www  
/var/www/html  
/var/www/html/test
/var/www/html/test/file.php

具有权限的文件列表:(编辑1)

1
2
3
4
5
6
[root@localhost ~]# ls -la /var/www/html/test
total 8
drwxrwxrwx. 2 root root  41 Aug 24 20:26 .
drwxrwxrwx. 4 root root  48 Aug 24 19:37 ..
-rwxrwxrwx. 1 root root 179 Aug 24 20:22 file.php
-rwxrwxrwx. 1 root root   1 Aug 24 20:22 newfile.txt

SELinux已启用并具有访问列表:

1
2
3
4
5
[root@localhost ~]# semanage fcontext -l |grep"var/www"
/var/www(/.*)?                                     all files          system_u:object_r:httpd_sys_content_t:s0
/var/www/html(/.*)?                                all files          system_u:object_r:httpd_sys_rw_content_t:s0
/var/www/(/.*)?                                    all files          system_u:object_r:httpd_sys_content_t:s0
/var/www/html/(.*)?                                all files          system_u:object_r:httpd_sys_rw_content_t:s0

(Edit2)*:如果我禁用SELinux,问题将会解决,问题出在SELinux上,我将提出一个新的问题,即为什么我也有访问列表时也会出错。


如果您具有root权限并成功完成了以下操作,这听起来很奇怪:

1
sudo chmod 777 -R /var/www

comand fopen应该可以正常运行,就像@Kimberlee设置的那样,您应该尝试为新文件提供绝对路径,如下所示:

1
2
3
$file = fopen('/var/www/html/test/newfile.txt', 'w');
fwrite($file,'something');
chmod('/var/www/html/test/newfile.txt', 0777);