环境变量和 PHP

2022-01-15 00:00:00 environment-variables php

我有一个 ubuntu 服务器,根据 ubuntu 社区推荐

I have an ubuntu server with a handful of custom environment variables set in /etc/environment as per the ubuntu community recommendation

当我从命令行使用 php 时,我可以使用 php 的 getenv() 函数来访问这些变量.

When I use php from the command line I can use php's getenv() function to access this variables.

另外,如果我从命令行运行 phpinfo(),我会在 ENVIRONMENT 部分看到我的所有变量.

Also, if I run phpinfo() from the command line I see all of my variables in the ENVIRONMENT section.

但是,当尝试访问由 php5-fpm 运行的进程内的相同数据时,此数据不可用.我可以在 phpinfo() 的 ENVIRONMENT 部分看到的是:

However, when trying to access the same data inside processes being run by php5-fpm this data is not available. All I can see in the ENVIRONMENT section of phpinfo() is:

USER    www-data
HOME    /var/www

我知道命令行使用这个ini:

I know the command line uses this ini:

/etc/php5/cli/php.ini

而fpm使用:

/etc/php5/fpm/php.ini

我没有设法找到两者之间的任何差异,这可以解释为什么 ENV 变量在两者中都没有出现.

I've not managed to find any differences between the two that would explain why the ENV variables are not coming through in both.

如果运行:

sudo su www-data

然后回显我期望它们确实可供 www-data 用户使用的环境变量.

and then echo the environment variables I am expecting they are indeed available to the www-data user.

我需要怎么做才能让我的环境变量进入 fpm 运行的 php 进程?

What do I need to do to get my environment variables into the php processes run by fpm?

推荐答案

原来你必须在 php-fpm.conf 中显式设置 ENV vars

It turns out that you have to explicitly set the ENV vars in the php-fpm.conf

这是一个例子:

[global]
pid = /var/run/php5-fpm.pid
error_log = /var/log/php5-fpm.log

[www]
user = www-data
group = www-data
listen = /var/run/php5-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chdir = /
env[MY_ENV_VAR_1] = 'value1'
env[MY_ENV_VAR_2] = 'value2'

相关文章