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

时间:2018-03-07 08:43:48

标签: php apache httpd.conf

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

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

请查看详细信息:

  1. Apache服务以用户身份运行:apache,选中:

    ps aux | egrep '(apache|httpd)'

  2. 2.要写入的文件和php脚本的所有权更改为apache。

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

    3.文件权限更改为:777

    chmod 777 test.txt 
    chmod 777 test.php
    

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

    操作系统:Redhat Enterprise

    代码:

    <?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) } 
    

1 个答案:

答案 0 :(得分:1)

终于到了答案了!我必须使用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/