温馨提示×

CentOS如何设置PHP权限

小樊
41
2026-08-29 14:32:37
栏目: 编程语言

CentOS 上设置 PHP 权限,通常要围绕 用户、目录权限、SELinux、Nginx/Apache 来配置。下面按常见场景系统说明。


一、确认 PHP 运行用户

1️⃣ CentOS + Apache

ps aux | grep httpd

通常:

  • 用户:apache

2️⃣ CentOS + Nginx + PHP-FPM

ps aux | grep php-fpm

通常:

  • 用户:apachenginx(取决于 php-fpm 配置)

查看 php-fpm 配置:

cat /etc/php-fpm.d/www.conf | grep -E '^user|^group'

默认常见:

user = apache
group = apache

PHP 以哪个用户运行,就必须给该用户目录权限


二、网站目录权限设置(最常见)

假设网站目录:

/var/www/html

✅ 推荐标准权限

# 设置目录所有者
chown -R apache:apache /var/www/html

# 目录权限
find /var/www/html -type d -exec chmod 755 {} \;

# 文件权限
find /var/www/html -type f -exec chmod 644 {} \;

三、上传 / 缓存 / 写目录权限

uploadsruntimecache 等需要写权限:

chown -R apache:apache /var/www/html/uploads
chmod -R 755 /var/www/html/uploads

如果仍然无法写入:

chmod -R 777 /var/www/html/uploads

⚠️ 不推荐长期使用 777,仅用于排查问题


四、SELinux 权限(CentOS 特有重点)

CentOS 默认开启 SELinux,这是 最常见“权限没问题但仍报错”的原因

1️⃣ 查看 SELinux 状态

getenforce
  • Enforcing ✅ 开启
  • Permissive / Disabled ❌ 关闭

2️⃣ 正确设置 SELinux(推荐)

✅ 允许 Web 服务器读写

chcon -R -t httpd_sys_rw_content_t /var/www/html/uploads

✅ 允许访问网站目录

chcon -R -t httpd_sys_content_t /var/www/html

3️⃣ 临时测试(不推荐生产)

setenforce 0

永久关闭(不推荐):

vi /etc/selinux/config
SELINUX=disabled

五、PHP 写文件权限示例

✅ PHP 写文件示例

file_put_contents('/var/www/html/test.txt', 'hello');

若报:

Permission denied

排查顺序:

  1. chown 是否正确
  2. chmod 是否正确
  3. SELinux 是否限制

六、PHP 执行命令权限(如 exec、shell_exec)

1️⃣ 确认 PHP 未禁用函数

php -i | grep disable_functions

2️⃣ 关闭 disable_functions(不推荐生产)

disable_functions =

七、常见错误速查表

问题 原因
PHP 无法写文件 目录权限 / SELinux
上传失败 uploads 目录
访问 403 目录无执行权限
执行 exec 无反应 disable_functions
Nginx 502 php-fpm 用户不匹配

八、推荐安全权限(生产环境)

chown -R apache:apache /var/www/html
find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;

写目录单独设置:

chown -R apache:apache uploads
chmod 755 uploads

如果你愿意,可以告诉我:

  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ Apache 还是 Nginx
  • ✅ PHP 版本
  • ✅ 具体错误提示

我可以帮你 精确给出一套权限方案

0