Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 725
wecsam Avatar asked Jul 05 '13 07:07

wecsam


People also ask

How do you check environment variable is set or not?

On Windows In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%. If the variable is set, its value is displayed in the command window.

How do you find the environment variable?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

Where are environment variables stored PHP?

This means the environment variables must be defined in a PHP-FPM configuration file, typically stored in /usr/local/etc/php-fpm.


1 Answers

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.

like image 54
wecsam Avatar answered Sep 18 '22 12:09

wecsam