(Originally posted on my Portuguese blog at rberaldo.com.br)
Where do you store sensitive configurations for your PHP project? If you define them directly in your code, you may be running a significant security risk.
Configurations like database usernames, SMTP passwords, and other sensitive information should be kept in a secure location. Most importantly, they should be kept out of version control for your software (such as Git, SVN, and others).
In this article, I will demonstrate how to use DotEnv in an extremely straightforward manner. With just two lines of code, all the critical settings for your project will be available as environment variables.
This is the idea behind the DotEnv project. Sensitive configurations are stored in a file called .env
(the dot means that it’s a hidden file in Unix-Like systems).
All the variables defined in .env
are automatically loaded into environment variables. That means, to retrieve their values, you can use the getenv()
function or the $
_ENV array.
Installing DotEnv
To install DotEnv, I will use Composer. If you’re not using Composer, what are you waiting for? Check out my article on Composer basics.
Open your terminal or command prompt in the root directory of your application and enter this command:
composer require vlucas/phpdotenv
After a few seconds, DotEnv will be fully downloaded, and you’ll see this output:
Using version ^2.0 for vlucas/phpdotenv
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing vlucas/phpdotenv (v2.0.1)
Downloading: 100%
Writing lock file
Generating autoload files
Creating the .env File
You need to create a file named .env
in the project’s root directory to store the variables. It’s important to include the dot at the beginning because it designates a hidden file, just like .htaccess, for example.
In the file, simply define variables using this syntax:
VARIABLE_NAME=VARIABLE_VALUE
This file follows the same pattern as a Shell Script file. You can even insert comments by starting the line with a hashtag:
# Explanation about the variable
VARIABLE_NAME=VARIABLE_VALUE
If you’re using version control (like Git or SVN), remember not to version the .env file for security reasons. Place it in .gitignore to ensure it’s ignored.
It’s recommended to create a file named .env.example
, with the same variables as .env
but with generic example values. This way, it’s easy to create the real file from the example. Just copy .env.example to .env and change the values.
Loading Environment Variables
Now that you have DotEnv installed and the .env file created, you need to load the file’s variables into environment variables.
This is incredibly easy! Only two lines!
Create the index.php file with this content:
<?php
// Composer's autoload
require 'vendor/autoload.php';
// The two lines that load the .env variables into environment variables
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
That’s it! All the variables from the .env file are now defined as environment variables.
You can confirm this as follows:
print_r($_ENV);
You’ll see your variables in the displayed array.
To fetch a single variable, you can use the $_ENV array or the getenv() function:
echo $_ENV['VARIABLE_NAME'];
// or echo getenv('VARIABLE_NAME');
Conclusion
DotEnv is the safest way to store sensitive configurations for your project.
You can combine this technique with a Bootstrapping concept, which I explain in this article. This way, you’ll have a secure, fast, and reliable system.
Simples objetivo e útil. Parabéns pelo post.
Olá, Gabriel
Obrigado!
A ideia é bem simples. E é ainda mais simples de implementar. E traz mais Segurança, que é algo fundamental. 🙂
Olá, é melhor instânciar o Slim e seus códigos antes do DotEnv?
Olá. Se o Slim usar alguma configuração do .env, precisa instanciá-lo antes do Slim.
Ótimo artigo, somente um detalhe que fiquei na dúvida que não vi no artigo. O arquivo .env pode ser acessado via URL como o .htaccess, neste caso seria interessante adicionar a regra no Apache ou Nginx para não permitir acesso a estes arquivos certo? OU deixá-lo fora da pasta pública como você comenta sobre o arquivo config.ini no artigo de Bootstrapping.
Olá, Lucas.
O ideal é sempre deixar arquivos de configuração e de lógica fora da pasta pública, seguindo a estrutura dos principais frameworks.
Porém, por padrão, os arquivos ocultos não são acessíveis via URL. Então não precisa de regra para o .env.