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

Tofunmi Falade
2 min readSep 21, 2018

--

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:

http://php.net/manual/en/function.getenv.php
http://php.net/manual/en/function.putenv.php

HOW DO I IMPLEMENT THEM IN MY PROJECT?

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.

--

--

Tofunmi Falade

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