Web Development

Dealing with Environment variable in PHP

Environment variables is the array of the values related to environment in which your application is running, just like OS, Computer Name, etc. PHP has provided few functions to deal with these variables. I mean we can add, remove variables from default values.

Here we will see how to add new environment variables using PHP, how to get value of environment varible in PHP, how to remove environment variable in PHP and how to change the value of the environment.

Add Environment Variable in PHP

We have ready PHP core function to add new environment varible. But make a note that, variable added using this method will only available during the script execution. It will get removed after the script execution is completed.

This function takes only one parameter as a [code]Key=Value[/code] pair. Have a look at below code to see how it works.

[cc lang=”php”]
// This will set SITE_LANG to DE
putenv(“SITE_LANG=DE”);

// This will set SITE_LANG to DE
putenv(“custom_value=value here”);
[/cc]

Get Environment Variable Value in PHP

Just like adding the new value, getting the environment variable value is also very simple. You just need to call one PHP core function and pass the key of the varible. Have a look at below code block for the same:

[cc lang=”php”]
// This will set SITE_LANG to DE
putenv(“SITE_LANG=DE”);

// This will print “DE”
echo getenv(“SITE_LANG”);
[/cc]

Edit/Remove Environment Variable Value

For editing and removing the environment variable you need to use the same function which we used while creating the environment. Have a look at below code block for the same:

[cc lang=”php”]
// Edit Environment Variable

putenv(“key=value”);
echo getenv(‘key’); // Will print “value”

putenv(“key=new_value”);
echo getenv(‘key’); // Will print “new_value”

// Remove Environment variable

putenv(“key=value”);
echo getenv(‘key’); // Will print “value”

putenv(“key”);
echo getenv(‘key’); // Will print nothing
[/cc]

In above code block you can see that, to remove the variable you just need to insert it blank. :)

This is how can you deal with the Environment variables in PHP. Subscribe to our feed, follow us and like us to get all latest updates and freebies.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *