PHP: 更改权限和所有权后文件不可写

PHP: File not writable after changing permissions and ownership

在 PHP 脚本中,检查文件是否可写时出现以下错误。

fopen(test.txt): failed to open stream: Permission denied

请看打击详情:

  1. Apache 服务 运行 为 user:apache,已检查:

    ps aux | egrep '(apache|httpd)'

待写入文件

2.Ownership,php脚本改为apache

chown apache:apache test.txt 
chown apache:apache test.php

3.File 权限已更改 to:777

chmod 777 test.txt 
chmod 777 test.php

4.Tried 设置: 已经尝试过的解决方案提供于:fopen Permission denied on a file with 777 permissions

OS:红帽企业

代码:

<?php
echo getmyuid().':'.getmygid(); 
echo "<br/>";
echo exec('whoami');
echo "<br/>";
$dst = 'test.txt';
echo $dst, file_exists($dst) ? ' exists' : ' does not exist<br/>', "<br/>\n";
echo $dst, is_readable($dst) ? ' is readable' : ' is NOT readable', "<br/>\n";
echo $dst, is_writable($dst) ? ' is writable' : ' is NOT writable<br/>', "<br/>\n";
$fh = fopen($dst, 'w');
if ( !$fh ) {
    echo ' last error: ';
    var_dump(error_get_last());
}

输出:

33:33
apache
test.txt exists
test.txt is readable
test.txt is NOT writable

last error: array(4) { ["type"]=> int(2) ["message"]=> string(57) "fopen(test.txt): failed to open stream: Permission denied" ["file"]=> string(34) "/var/www/data/test2.php" ["line"]=> int(10) } 

终于自己找到答案了!我必须使用 chon 命令修改 SELinux 配置并应用权限为:httpd_sys_rw_content_t

chcon -R -h -t httpd_sys_rw_content_t /var/www/data/

连同:

chown -R apache:apache/var/www/data/
chmod -R a+rX /var/www/data/