How to create an environment variable file like Laravel & Symphony’s .env

Henry Falade
Sep 21, 2018 · 2 min read

Have you ever thought of how you can deploy your web-applications and you don’t have to neither set your Database Configurations with your server’s credentials before deployment, nor go on to your server to edit the credentials to follow suit?

If you are familiar with PHP frameworks like Laravel and Symphony, you should know about their .env file. It is where you set all your local variable ranging from database credentials to mail-service credentials and whatever you think should be peculiar to environment (Local/Development, Staging and Production).

WHAT IS getenv() AND putenv()?

These two PHP functions are the secret behind Laravel’s .env file. Like their name suggests, one is used to set environment variables putenv() while the other is used to get the variables getenv().

You can read more on them below:


Implementing them is very simple, and as you guessed, yes! It will involve loops.

CREATE AN env.example.php FILE

I know you will be wondering, what’s with the .example? This is the file that you will copy and paste as env.php. Remember it is a file that should be peculiar to its environment, thus, you will add your env.php to .gitignore. We will get back to that later.

Before then, put the snippet below into your file.

You can add more variables to it.

CREATE AN autoload.php FILE

Depending on how you autoload files in your project, composer/the old fashion include. If you use composer, rename this file to something else, it can be named anything actually.

However, for the sake of this write-up, we will stick to autoload.php.

Put the snippet below into your file.

Make sure it is in the same directory with your env.example.php file

Notice that in our autoload.php we are including env.php and not env.example.php?
That is because, an env.php will be recreated from env.example.php per the environment your app is deployed on, and because of its peculiarity, you should add it to your .gitignore.

Once your are done setting this up, like I stated earlier, depending on how you autoload files within your directory, autoload your autoload.php file. For non-composer project, just include this file in your project generally via include "autoload.php";

Voilà! you can access your environment variables through env('VARIABLE_NAME')

Feel free to leave your questions, comments or contributions below, thanks.

Henry Falade

Written by

A programmer and web tech enthusiast! Love Angular & Laravel.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade