在 CentOS 上,PHP 日志无法写入或权限不足是比较常见的问题,通常出现在 PHP-FPM / Apache + PHP 场景中。下面按常见原因 → 排查 → 解决方案系统性说明。
/var/log/php-fpm/error.log
error_log = /var/log/php_error.log
/var/log/nginx/
/var/log/php-fpm/
/var/log/httpd/
failed to open stream: Permission denied
或
PHP Warning: error_log(): failed to open stream
ps aux | grep php-fpm
常见用户:
apache
nginx
www-data(少见于 CentOS)
查看配置:
grep -R "user\|group" /etc/php-fpm.d/www.conf
示例:
user = nginx
group = nginx
ls -l /var/log/php_error.log
-rw-r--r-- 1 nginx nginx 0 Apr 10 10:00 php_error.log
chown nginx:nginx /var/log/php_error.log
chown -R nginx:nginx /var/log/php-fpm
chmod 755 /var/log/php-fpm
SELinux 是 CentOS 权限问题的“隐形杀手”
getenforce
Enforcing → 很可能是 SELinux 阻止Permissive / Disabled → 与 SELinux 无关ausearch -m avc -ts recent
setenforce 0
semanage fcontext -a -t httpd_log_t "/var/log/php_error.log"
restorecon -v /var/log/php_error.log
或允许写入日志目录:
semanage fcontext -a -t httpd_log_t "/var/log/php-fpm(/.*)?"
restorecon -Rv /var/log/php-fpm
php -i | grep error_log
确保:
log_errors = On
error_log = /var/log/php_error.log
修改后重启服务:
systemctl restart php-fpm
systemctl restart httpd
systemctl restart nginx
✅ 不要 把日志改成 777
✅ 不要 用 root 运行 PHP
✅ 使用正确属主 + SELinux
error_log = /var/log/php-fpm/php_error.log
chown nginx:nginx /var/log/php-fpm/php_error.log
semanage fcontext -a -t httpd_log_t "/var/log/php-fpm(/.*)?"
restorecon -Rv /var/log/php-fpm
ps aux | grep php-fpm
ls -l /var/log/php*
getenforce
php -i | grep error_log
如果你愿意,可以把以下信息发我,我可以精确判断原因:
ls -l 日志文件输出我可以直接给你一条可执行的修复命令 ✅