Apache运行的PHP脚本无写入权限问题排查及解决方案咨询
问题:Apache用户无法写入自身拥有的777权限文件夹
我编写了一段检测PHP进程对指定文件夹写入权限的脚本:
<?php $folder = '/var/www/html/easyappointments/storage/'; // $folder = '/tmp/'; $testfile = '.testfile'; // 获取运行用户 $whoami = `whoami`; echo "运行PHP脚本的用户是:$whoami <BR>"; // 检查文件夹权限 $perms = fileperms($folder); $perms = substr(sprintf('%o', $perms), -4); echo "文件夹 $folder 的八进制权限为:$perms <BR>"; // 检查文件夹所有者 $owner = posix_getpwuid(fileowner($folder)); echo "文件夹 $folder 的所有者是:$owner[name] <BR>"; if (is_writable($folder)) { if ($fp = fopen($folder . $testfile, 'w')) { echo "文件 $folder$testfile 可写入"; fclose($fp); unlink($folder . $testfile); } else { echo "文件 $folder$testfile 不可写入"; } } else { echo "文件夹 $folder 不可写入,当前权限为:$perms <BR>"; } ?>
在Chrome中运行脚本后,输出结果如下:
运行PHP脚本的用户是:apache 文件夹 /var/www/html/easyappointments/storage/ 的八进制权限为:0777 文件夹 /var/www/html/easyappointments/storage/ 的所有者是:apache 文件夹 /var/www/html/easyappointments/storage/ 不可写入,当前权限为:0777
我的环境是:CentOS 7、PHP 7.3.33、Apache 2.4.6。我无法理解为何运行脚本的apache用户,无法写入自己拥有且权限为777的文件夹,请问如何确保PHP脚本拥有指定文件夹的写入权限,以及如何正确授权?
解决方案
1. 检查SELinux限制(最常见原因)
CentOS 7默认开启SELinux,即使文件权限正确,SELinux也会阻止Apache写入目录。
- 检查SELinux状态:
如果输出中sestatusCurrent mode为enforcing,说明SELinux在生效。 - 临时关闭SELinux(仅用于测试):
重新运行脚本,如果可以写入,说明是SELinux的问题。setenforce 0 - 永久设置正确的SELinux上下文(推荐):
# 设置目录上下文为Apache可读写类型 chcon -R -t httpd_sys_rw_content_t /var/www/html/easyappointments/storage/ # 永久保存上下文规则(需先安装policycoreutils-python包) yum install policycoreutils-python -y semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/easyappointments/storage(/.*)?" restorecon -Rv /var/www/html/easyappointments/storage/
2. 检查文件系统挂载参数
查看目标文件夹所在分区的挂载选项,确保没有写入限制:
- 查看挂载信息:
如果挂载选项包含mount | grep $(df -P /var/www/html/easyappointments/storage/ | tail -1 | awk '{print $1}')ro(只读),则无法写入,需要修改/etc/fstab中的挂载选项为rw,然后重新挂载。
3. 检查PHP安全限制
确认PHP的open_basedir配置没有限制目标文件夹:
- 创建一个
phpinfo.php文件,内容为:
访问该文件,查找<?php phpinfo(); ?>open_basedir项。如果其值不包含/var/www/html/easyappointments/storage/,需要修改php.ini(或Apache的虚拟主机配置)中的open_basedir,添加目标文件夹,然后重启Apache。
4. 检查文件特殊权限
查看文件夹是否被设置了不可修改的特殊权限:
- 检查特殊权限:
如果输出包含lsattr /var/www/html/easyappointments/storage/i(不可修改)或a(仅追加),则需要移除该权限:# 移除不可修改权限 chattr -i /var/www/html/easyappointments/storage/ # 若有仅追加权限也一并移除 chattr -a /var/www/html/easyappointments/storage/
内容的提问来源于stack exchange,提问作者jasonL
相关产品推荐
相关产品推荐

