selinux 激活情况下,php 写文件操作失败

本文解决在Fedora20环境下Apache与PHP运行时,因SELinux导致的写文件权限不足问题。通过设置SELinux上下文、修复文件类型及启用特定布尔值,最终成功实现文件写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

httpd_selinux 详细内容请参考: http://linux.die.net/man/8/httpd_selinux


php运行在apache上,写文件失败,提示 fopen()  permission denied. 出现这种情况的原因很多,可能是apache用户没有权限(php一般以apache用户运行代码)等等,这里只说明selinux导致的权限不足问题;

运行环境:fedora 20 + apache + php


假定我们要写文件的目录为 /var/www/html/test_dir ,则执行以下命令:

semanage fcontext -a -t public_content_rw_t "/var/www/html/test_dir(/.*)?"

restorecon -F -R -v /var/www/html/test_dir

setsebool -P allow_httpd_anon_write 1

重启apache服务器:systemctl restart httpd.service

写一段测试代码试一下:

<?php
    $fp = fopen("test_dir/test.txt", "w");
    fwrite($fp, "aaaaaa");
    fclose($fp);
    echo "write file ok.";
?>

成功写入test.txt文件。


原文描述:

Sharing Files

If you want to share files with multiple domains (Apache, FTP, rsync, Samba), you can set a file context of public_content_t and public_content_rw_t. Thesecontext allow any of the above domains to read the content. If you want a particular domain to write to the public_content_rw_t domain, you must set theappropriate boolean.

Allow httpd servers to read the /var/httpd directory by adding the public_content_t file type to the directory and by restoring the file type.semanage fcontext -a -t public_content_t "/var/httpd(/.*)?"
restorecon -F -R -v /var/httpd
Allow httpd servers to read and write /var/tmp/incoming by adding the public_content_rw_t type to the directory and by restoring the file type. This alsorequires the allow_httpdd_anon_write boolean to be set.semanage fcontext -a -t public_content_rw_t "/var/httpd/incoming(/.*)?"
restorecon -F -R -v /var/httpd/incoming

If you want to allow Apache to modify public files used for public file transfer services. Directories/Files must be labeled public_rw_content_t., you mustturn on the allow_httpd_anon_write boolean.

setsebool -P allow_httpd_anon_write 1

If you want to allow apache scripts to write to public content. Directories/Files must be labeled public_rw_content_t., you must turn on theallow_httpd_sys_script_anon_write boolean.

setsebool -P allow_httpd_sys_script_anon_write 1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值