在CentOS系统中调整PHP配置需结合应用场景(如性能优化、功能扩展、安全需求)和服务器资源(如内存、CPU),以下是具体步骤和常见需求的配置方法:
修改PHP核心参数(/etc/php.ini)
memory_limit(如256M),根据应用复杂度(如WordPress、Laravel)增加内存,避免脚本因内存不足终止。max_execution_time(如300秒),适用于需要长时间运行的脚本(如数据导入、批量处理)。upload_max_filesize(如50M)和post_max_size(如50M),允许用户上传更大文件(如图片、视频)。date.timezone(如Asia/Shanghai),确保时间显示正确。display_errors = Off(隐藏错误信息)、log_errors = On(记录到/var/log/php_errors.log),避免敏感信息泄露。启用OPcache(提升性能)
OPcache可缓存编译后的PHP脚本,减少重复解析时间。编辑/etc/php.ini添加:
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128 # 内存大小(MB),根据服务器内存调整
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000 # 缓存文件数,建议设置为项目文件总数的1.5倍
opcache.revalidate_freq=60 # 文件修改后重新验证的时间(秒)
重启PHP-FPM使配置生效:sudo systemctl restart php-fpm。
若使用PHP-FPM(推荐用于Nginx/Apache),需调整进程池参数(/etc/php-fpm.d/www.conf):
pm = dynamic(动态调整进程数,适合大多数场景),或pm = ondemand(按需创建进程,适合低流量场景)。pm.max_children:最大子进程数,计算公式为(可用内存 - 1G) / 单个进程内存(如服务器有4G内存,单个进程约占用100M,则pm.max_children = 30)。pm.start_servers:启动时的进程数(如5)。pm.min_spare_servers/pm.max_spare_servers:最小/最大空闲进程数(如5/35),保持空闲进程应对突发请求。pm.max_requests = 500,每个子进程处理500个请求后重启,防止内存泄漏。Nginx配置(/etc/nginx/conf.d/default.conf)
确保Nginx能正确传递PHP请求到PHP-FPM:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php-fpm/www.sock; # 使用Unix套接字(更高效)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
重启Nginx:sudo systemctl restart nginx。
Apache配置(/etc/httpd/conf.d/php.conf)
若使用Apache,需启用mod_proxy_fcgi并配置:
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
</FilesMatch>
重启Apache:sudo systemctl restart httpd。
/etc/php.ini中设置disable_functions = exec,passthru,shell_exec,system,禁止执行系统命令,防止恶意代码注入。open_basedir限制PHP脚本只能访问指定目录(如/var/www/html),避免越权访问。firewall-cmd开放HTTP(80)和HTTPS(443)端口,关闭不必要的端口:sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
top、htop查看CPU、内存占用,php-fpm -t测试配置语法,tail -f /var/log/php-fpm/error.log查看错误日志。sudo systemctl restart php-fpm。sudo yum update php*更新PHP及相关扩展,修复安全漏洞。以上步骤覆盖了CentOS下PHP配置的常见需求调整,可根据实际应用场景(如电商网站、博客、API服务)灵活修改参数,确保PHP运行稳定且高效。