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

iqb*_*lmp 2 php apache httpd.conf

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

fopen(test.txt): failed to open stream: Permission denied
Run Code Online (Sandbox Code Playgroud)

请看打击详情:

  1. Apache 服务以用户:apache 身份运行,检查如下:

    ps aux | egrep '(apache|httpd)'

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

chown apache:apache test.txt 
chown apache:apache test.php
Run Code Online (Sandbox Code Playgroud)

3.文件权限改为:777

chmod 777 test.txt 
chmod 777 test.php
Run Code Online (Sandbox Code Playgroud)

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

操作系统:红帽企业版

代码:

<?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());
}
Run Code Online (Sandbox Code Playgroud)

输出:

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) } 
Run Code Online (Sandbox Code Playgroud)

iqb*_*lmp 5

我自己终于得出了答案!我必须使用 chon 命令修改 SELinux 配置并应用权限,如下所示:httpd_sys_rw_content_t

chcon -R -h -t httpd_sys_rw_content_t /var/www/data/
Run Code Online (Sandbox Code Playgroud)

随着:

chown -R apache:apache/var/www/data/
chmod -R a+rX /var/www/data/
Run Code Online (Sandbox Code Playgroud)