我在 Centos 上使用 PHP 作为 PHP-FPM。我正在尝试关注 http://12factor.net/将设置存储在环境变量中的指南。
我在/etc/profile.d 中创建了一个文件,用于设置我想要的环境变量,环境变量在通过 Bash 在 CLI 中测试时出现,即运行 bash 脚本:
echo $SOME_SERVER_SETTING
显示正确的输出。
我已将 clear_env 设置为 false,将 variables_order 设置为 EGPCS
,但是,我设置的变量也没有显示在 PHP 中 getenv('SOME_SERVER_SETTING')
或者做 var_dump($_ENV)
需要设置哪些其他设置才能让 PHP-FPM 接收所有服务器环境变量,特别是那些通过 Centos 上的/etc/profiles.d 中的 shell 脚本设置的环境变量?
最佳答案
在带有 Systemd 服务和 PHP 5.6.4 的 Centos 7 上测试
打开
/etc/php.ini
寻找
variables_order = "GPCS"
替换为
variables_order = "EGPCS"
# http://php.net/manual/en/ini.core.php#ini.variables-order
打开
/etc/php-fpm.d/www.conf (maybe /etc/php5/fpm/pool.d/www.conf)
(do not confuse with /etc/php-fpm.conf)
查找如果存在
clear_env = yes
替换或添加
clear_env = no
# http://php.net/manual/en/install.fpm.configuration.php
打开
/etc/environment
添加
#any variables you need, for example:
MY_VAR=1234
在 shell 中运行以进行检查
source /etc/environment
echo $MY_VAR # 1234
在外壳中运行
ln -fs /etc/environment /etc/sysconfig/php-fpm
systemctl daemon-reload && service php-fpm restart
...测试
打开
index.php # in your project folder, running with php-fpm
添加
var_dump(getenv('MY_VAR'), $_ENV['MY_VAR']);exit;
在浏览器中运行
http://mylink.to.project/index.php
string(4) "1234"
string(4) "1234"
尽情享受吧!
关于php - 如何让PHP能够读取系统环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822695/