Search code examples
phpenvironment-variablesisset

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


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

Solution

  • 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.