How do I check whether an environment variable is set in PHP?
23,826
Solution 1
getenv()
returns false
if the environment variable is not set. The following code will work:
// Assuming MYVAR isn't defined yet.
getenv("MYVAR") !== false; // returns false
putenv("MYVAR=foobar");
getenv("MYVAR") !== false; // returns true
Be sure to use the strict comparison operator (!==
) because getenv()
normally returns a string that could be cast as a boolean.
Solution 2
you can check like this
if($ip = getenv('REMOTE_ADDR'))
echo $ip;
getenv() Returns the value of the environment variable.
Comments
-
wecsam almost 2 years
In PHP, how do I test whether an environment variable is set? I would like behavior like this:
// Assuming MYVAR isn't defined yet. isset(MYVAR); // returns false putenv("MYVAR=foobar"); isset(MYVAR); // returns true
-
wecsam almost 11 years
isset($var)
is always true in this case. -
wecsam almost 11 yearsIsn't
REMOTE_ADDR
always set? In my case, I'm writing a script that needs to act differently based on whether the server has an environment variable set. -
Rajeev Ranjan almost 11 years@wecsam REMOTE_ADDR was just an example you can pass different environment variable
-
wecsam almost 11 yearsI figured out by myself that
getenv()
returnsfalse
if the environment variable is not set. I see that that is what your code tries to illustrate. However, there are several problems with your code. First of all, we try to avoid using the=
assignment operator inif
conditionals because we almost always meant==
. Second of all, the value of the environment variable could be an empty string that casts tofalse
, so we need to use a strict comparison operator. -
Rajeev Ranjan almost 11 years@wecsam I think its not comparison ,assign getenv('REMOTE_ADDR') value to $ip and then checking for $ip .
-
wecsam almost 11 yearsI know that it's not a comparison. What I'm saying is that we usually don't do assignments in
if
conditionals. -
mostafa khansa almost 11 years@wescam is right, you can't do assignment inside an if condition
-
nickdnk almost 7 yearsSince getvar() returns false when not set, isset will return true always, since $var is set, but set to false.
-
boumbh almost 4 yearsI don't know why, but my PHP (7.1.32) returns an empty string when MYVAR is not defined... I tried
key_exists('MYVAR', getenv())
, but it didn't work either, so I ended up checking for!empty(getenv('MYVAR'))
... -
Fabien Snauwaert over 2 yearsFor people using DotEnv: values of OFF will be a string and so evaluate to
true
with this approach. -
Al-Amin over 2 yearsWhat happened if my env variable
ENV_VARIABLE=false
?