I want to set an environment-variable, then access it in PHP, but cannot find how to do so.
In the (linux) shell, I run:
$ APP_ENV="development"
$ export $APP_ENV
Then I run a simple test script testenv.php:
<?php
print $_ENV["APP_ENV"];
print getenv("APP_ENV");
From the same shell where that variable was set:
$ php testenv.php
This Prints nothing and throws a notice:
Notice: Undefined index: APP_ENV in /xxxx/envtest.php on line 2
Notice makes sense, because APP_ENV is simply not found in the environment-variables, getenv()
throws no warning but simply returns nothing.
What am I missing?
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.
An . env file is a plain text file which contains environment variables definitions which are designed so your PHP application will parse them, bypassing the Apache, NGINX and PHP-FPM. The usage of . env files is popular in many PHP frameworks such as Laravel which has built-in support for parsing .
As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.
Don't use $
in the export
command, it should be:
export APP_ENV
You can combine this with the assignment:
export APP_ENV="development"
With the $
, you were effectively doing:
export development
Your export is incorrect.
$ APP_ENV="development"
$ export APP_ENV
Notice that the $
is missing from the export statement! :P
First check getenv to make sure that export works:
<?php
echo getenv ("APP_ENV");
?>
<?php
echo $_ENV["APP_ENV"];
?>
If you get a proper value from getenv
but not the superglobal $_ENV
then you may have to check your ini file.
Quoting php.org:
If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With