【问题标题】:Setting $_ENV (fka $HTTP_ENV_VARS) with nginx/php-fpm使用 nginx/php-fpm 设置 $_ENV (fka $HTTP_ENV_VARS)
【发布时间】:2012-01-23 00:12:07
【问题描述】:

什么是 apache 环境中的 setenv 等价物? 例如,使用 apache,我可以设置 env "SOMEE​​NV" 并通过 $_ENV['SOMEE​​NV'] 在 php 中访问它 - 但我不知道如何使用 nginx+php-fpm 进行操作。

我最初以为我只需在我的 php-fpm 池的配置中设置 ENV[SOMENEV]=test,但 var_dump($_ENV) 仍然没有返回任何内容。

有什么提示吗?

【问题讨论】:

    标签: nginx environment-variables php


    【解决方案1】:

    nginx 没有办法影响 php 的环境,因为它没有将 php 解释器嵌入到它的进程中。它通过fastcgi_param 指令将参数传递给php。您可以在设置其余参数的位置添加一个并通过 $_SERVER 访问它:

    location ~ \.php$ {
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_param SOMEENV test;
      fastcgi_pass php;
    }
    

    【讨论】:

    • 您好,感谢您的回复。好的,这允许我注入 $_SERVER['SOMEE​​NV'],但是我如何为 $_ENV['SOMEE​​NV'] 提供一些东西?
    • $_SERVER 数组条目是由网络服务器创建的,但 $_ENV 变量是从 PHP 解释器运行的环境导入的,并且许多变量是由运行 PHP 的 shell 提供的。在 Apache 的情况下,php 解释器嵌入到 Apache 进程中,但在 Nginx 中并非如此。 IOW,可以使用 Nginx 设置 $_ENV 变量,并且 $_SERVER 尽可能好。
    • NGINX 中不是有env 指令吗?
    • 可以,但是只影响nginx主进程和工作进程的环境(nginx.org/en/docs/ngx_core_module.html#env)。由于 php 不像在 apache 上运行 mod_php 那样在 nginx 内部运行,所以 nginx 实际上不会影响 php 的环境。
    【解决方案2】:

    请注意,$_ENV 变量的可用性取决于 php-fpm 使用的 php.ini 中 variables_order 的设置。默认值为EGPCS,其中E 是环境,但是在Ubuntu 12.04 上我发现它是GPCS。 php.ini 本身带有关于$_ENV 的警告:

    ; This directive determines which super global arrays are registered when PHP
    ; starts up. G,P,C,E & S are abbreviations for the following respective super
    ; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty
    ; paid for the registration of these arrays and because ENV is not as commonly
    ; used as the others, ENV is not recommended on productions servers.
    

    建议使用始终可用的getenv()。我发现我在 FPM 池中设置的变量可以通过这种方式检索。

    【讨论】:

    猜你喜欢
    • 2012-07-20
    • 2019-03-03
    • 1970-01-01
    • 2016-10-25
    • 2017-03-29
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多