Http://luokr.com/p/30
Usually when we maintain the PHP line project, in order to isolate the configuration and code, we will use fastcgi_param
the form to define the environment variables in the Nginx configuration file (Apache can use SetEnv
instructions). This allows you to use the getenv
function to get the values of the environment variables during the PHP-FPM run.
So how do we set the environment variables for PHP-CLI? The practice is also simple.
Execute directly on the terminal:
- $ export art_env=production
You can naturally get the value of the environment variable when you follow the direct use of the PHP-CLI command ART_ENV
:
- $ php -R "Var_dump (getenv (' art_env '));"
- String(ten) "Production"
But this is usually the case: the user we are currently logged on is not the right one to run the Php-cli script, such as we expect to use the www-data
user to run the Php-cli script, which we usually do:
- $ sudo -u www-data php -R "Var_dump (getenv (' art_env '));"
- BOOL(false)
You will find that you cannot get to the environment variable. Check sudo --help
to see that we also need to set -E
parameters:
- $ sudo -- Help
- ...
- -E, --Preserve-env Preserve user environment when running command /c11>
Follow the documentation to fill in the instructions:
- $ sudo -E -u www-data php -R "Var_dump (getenv (' art_env '));"
- String(ten) "Production"
Or, more directly, specify the value of the environment variable directly:
- $ sudo -u www-data art_env=testing php -R "Var_dump (getenv (' art_env '));"
- String(7) "testing"
It is important to note that the PHP code here must use the GETENV function to get the environment variables and not rely solely on global variables $_ENV
. Global variables are $_ENV
not always available unless the value explicitly set in the php.ini file variables_order
contains E, for example variables_order = "EGPCS"
. For more details, refer to the Global Variables section of the PHP documentation.
PHP-CLI setting and reading of environment variables