What is the difference between getenv()
and $_ENV
?
Any trade-offs between using either?
I noticed sometimes getenv()
g
I know that the comment in the docs says that getenv
is case-insensitive, but that's not the behaviour I'm seeing:
> env FOO=bar php -r 'print getenv("FOO") . "\n";'
bar
> env FOO=bar php -r 'print getenv("foo") . "\n";'
> env foo=bar php -r 'print getenv("foo") . "\n";'
bar
> env foo=bar php -r 'print getenv("FOO") . "\n";'
> php --version
PHP 5.4.24 (cli) (built: Jan 24 2014 03:51:25)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
Looking at the source code for the getenv
function, this is because there are three ways that PHP can fetch the environment variable:
sapi_getenv
(e.g. if it's getting the environment variable from Apache)GetEnvironmentVariableA
.getenv
function provided by libc
.As far as I can tell, the only time when it will behave in a case-insensitive manner is on Windows because that's how the Windows environment variable API behaves. If you're on Linux, BSD, Mac, etc then getenv
is still case sensitive.
As mentioned by mario, $_ENV
is not always populated due to different configurations of variables_order
so it's best if you avoid $_ENV
if you don't control the server configuration.
So, for the most portable PHP code:
getenv
.