Home | About | Blog | Interesting Reads | Tutorials | Skills | Personal Projects | Books | Fun | Connect with me
Published On: Apr 10 2022
Written By: Krishnan Sethuraman
Category: PHP
Managing environment variables can be challenging while building software with Php. For the sake of convenience or out of ignorance developers commit the environment variables along with the source code (I have done this). However this can be a huge security issue and the credentials which need to be protected can end up falling in the hands of anti-social elements.
While frameworks like Laravel make it easy to manage environment variables, things can become difficult if we are using a micro framework or simply using core Php.
Php dotenv is the ideal solution for this problem. This package makes it really easy for developers using just php to manage and use environment variables.
It can be added to your source code with composer.
$ composer require vlucas/phpdotenv
Once it is installed the environment variables can be managed by creating a .env file in the project root directory and populating it with all environment variables. Below is an example of a .env file.
DB_SERVER=''
DB_USER_NAME=''
DB_USER_PSWD=''
SENDGRID_API_KEY=''
FROM_EMAIL=''
BEANSTALKD_HOST=''
BEANSTALKD_PORT=''
This can then be used in the code with something like this.
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$db_server = $_ENV['DB_SERVER'];
$db_name = $_ENV['DB_NAME’];
$db_username = $_ENV['DB_USER_NAME'];
$db_password = $_ENV['DB_USER_PSWD'];
Voila you can refer and use the environment variables in your code without having to commit them to the repository.