How do I check whether an environment variable is set in PHP?

wecsam picture wecsam · Jul 5, 2013 · Viewed 20.6k times · Source

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

Answer

wecsam picture wecsam · Jul 5, 2013

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.