20

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
  • 2,651
  • 4
  • 25
  • 46

3 Answers3

41

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.

wecsam
  • 2,651
  • 4
  • 25
  • 46
  • 2
    I 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'))`... – boumbh Aug 25 '20 at 16:06
  • For people using DotEnv: values of OFF will be a string and so evaluate to `true` with this approach. – Fabien Snauwaert Feb 01 '22 at 14:52
  • 1
    What happened if my env variable `ENV_VARIABLE=false` ? – Al-Amin Feb 10 '22 at 18:16
5

you can check like this

if($ip = getenv('REMOTE_ADDR'))
echo $ip; 

getenv() Returns the value of the environment variable.

Rajeev Ranjan
  • 4,152
  • 3
  • 28
  • 41
  • 1
    Isn'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. – wecsam Jul 05 '13 at 07:48
  • @wecsam REMOTE_ADDR was just an example you can pass different environment variable – Rajeev Ranjan Jul 05 '13 at 08:28
  • 3
    I figured out by myself that `getenv()` returns `false` 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 in `if` conditionals because we almost always meant `==`. Second of all, the value of the environment variable could be an empty string that casts to `false`, so we need to use a strict comparison operator. – wecsam Jul 05 '13 at 16:48
  • @wecsam I think its not comparison ,assign getenv('REMOTE_ADDR') value to $ip and then checking for $ip . – Rajeev Ranjan Jul 06 '13 at 04:17
  • 1
    I know that it's not a comparison. What I'm saying is that we usually don't do assignments in `if` conditionals. – wecsam Jul 07 '13 at 16:16
  • @wescam is right, you can't do assignment inside an if condition – mostafa khansa Sep 05 '13 at 12:18
-7

This is what you need

    $var = getenv(MYVAR)
    if(isset($var)) {

    } else {

    }
Engineer
  • 5,911
  • 4
  • 31
  • 58