DEV Community

Gavin Sykes
Gavin Sykes

Posted on • Edited on

Build a Modern API with Slim 4 - Set up your .env file

In the last post you may have spotted mention of a .env file. What is it? What does it do? Where does it sit? How does the application use it?

All of the above will be answered. For now though the very first thing you will want to do, before even creating it, is to add it to your .gitignore. This will contain all of our keys, database login info, and many other bits we don't want anyone to see. So gitignoring it will make sure none of those values are committed.

Make sure that we are in our project root, where our composer.json and composer.lock should be.

echo .env >> .gitignore
touch .env
Enter fullscreen mode Exit fullscreen mode

Now open your newly-created file in your favourite IDE and add some variables.

_ENVIRONMENT="development"
_PDO_HOST="ip.address.or.domainname"
_PDO_USERNAME="user.name"
_PDO_PASSWORD="SuperSecretPassword123"
_PDO_NAME="DatabaseName"
_ENCRYPTION_CIPHER_METHOD="AES-256-CTR"
_HASHING_COST="10"
_SMTP_HOST="smtp.mybookstore.com"
_SMTP_USERNAME="bookstore.ceo"
_SMTP_PASSWORD="ExtraSuperSecretPassword1234"
_RATE_LIMIT_GET="1200"
_RATE_LIMIT_POST="600"
_RATE_LIMIT_PUT="600"
_RATE_LIMIT_DELETE="300"
Enter fullscreen mode Exit fullscreen mode

You'll notice that some of those variables don't necessarily need to be kept secret. In particular, does the SMTP host not get included in every single email our system is going to send? Well, yes, however this file isn't just for secrets, it is also a handy place to store environment-specific variables such as, well, the first line! _ENVIRONMENT=development, staging, production, any others such as demo?

By having this file you can recreate it on each server in each environment and only have to change the relevant variables in one place. The same goes for the rate limits: they're going in our documentation, there's no way they're secret!

Top comments (0)