DOTENV in PHP
Tags: php, env, composer, tutorial
Published: 2022-09-11 17:35:24

When we are creating a project, there are always some sensitive values, and at the beginning we don't know where to write it and with that we end up writing it in my code, such as database passwords and others.

But this is a big problem, firstly in terms of security because your data is visible to everyone with access to the code and secondly, it gets complicated whenever you change environments such as production and so on.

And to solve this came `.env`, from which the point(dot) for linux environment is to leave files hidden, and the name **env** is an abbreviation for **environment**.

To understand better, let's see it in practice.

## CODE

First let's check the values that are in the environment variables and for that we can use `getenv()`;

```php
<?php
print_r(getenv());
```

_💡 NOTE: More information in the [documentation](https://www.php.net/manual/en/function.getenv.php)_

to create a new value we just need to use `putenv()`;

```php
<?php
putenv("TEST=test");
```

and to display the value we use

```php
<?php
echo getenv("TEST");
```

_💡 NOTE: It is a good practice to have environment variable names in uppercase_

In addition to **getenv** we also have **$_ENV**

**$_ENV** is an associative array where each of its keys is an environment variable pointing to its value. The problem is that it might not load depending on the `php.ini` configuration. To enable it, put the “E” option in the “variables_order” directive, where each letter represents a superglobal to be loaded. 

And to display the value we use

```php
<?php
echo $_ENV['APP_ENV'];
```

Now that we know where the variables are, how to create more and how to call just one, let's make php read the values from an `.env` file and save it in the environment variables inside php.

### DOTENV

First create the `.env` file.

```bash
touch .env
```

and inside put the values you want, for this example I will just put two variables

```.env
APP_NAME=Project
APP_ENV=local
```

### PHP CLASS

First let's create the class

```php
<?php
 
namespace App\Controller;
 
class DotEnvEnvironment
{
 
   public function load($path): void
   {
       $lines = file($path . '/.env');
       foreach ($lines as $line) {
           [$key, $value] = explode('=', $line, 2);
           $key = trim($key);
           $value = trim($value);
 
           putenv(sprintf('%s=%s', $key, $value));
           $_ENV[$key] = $value;
           $_SERVER[$key] = $value;
       }
   }
}
```

and now just use

```php
<?php
 
require __DIR__ . '/../vendor/autoload.php';
 
(new App\Controller\DotEnvEnvironment)->load(__DIR__ . '/../');
 
echo getenv('APP_ENV');
echo $_ENV['APP_NAME'];

```

### .gitignore

Never send the `.env` to the server from the code, because the purpose of the `.env` is to separate sensitive information from the code so it doesn't matter if you still send it to the server, and to avoid this just add the value to the `.gitignore` file.

```
.env
```

If you are developing as a team, you can include the `.env.example` file and add some fictitious values there so that those who use the project can understand what should be done example.

```.env
DATABASE=database-name
PASSWORD=your-password-here
```

### TIP

You can use different `.env` files per environment, so you can have `.env.staging` for staging, `.env.production` for production, `.env.testing` for testing, etc.

## Library

Despite having shown how to create a file that loads `.env`, I don't think it's the best solution, as there are already libraries ready, more robust and much more tested, so if you're just curious to understand how it works, go ahead and create your own, but if you want to create or use it in a professional project I recommend the [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) library, so excellent that the laravel framework itself uses and therefore I will show you how to use it.

_💡 NOTE: [symfony/dotenv](https://github.com/symfony/dotenv) is used in Symfony framework and sometimes i use it too_

First add it to composer

```composer
composer require vlucas/phpdotenv
```

Now we create the `.env` file

```.env
APP_NAME=Project
APP_ENV=local
```

Now we load the file

```php
<?php

require __DIR__ . '/../vendor/autoload.php';

Dotenv\Dotenv::createUnsafeImmutable(__DIR__ . '/../')->load();

echo getenv('APP_ENV');
echo $_ENV['APP_NAME'];

```

That's it, simple as that, with just a few lines you already have the project configured.

***

## Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you! 😊😊

***

## Support Me

[Youtube - WalterNascimentoBarroso](https://www.youtube.com/channel/UCXm0xRtDRrdnvkW24WmkBqA)
[Github - WalterNascimentoBarroso](https://github.com/walternascimentobarroso)
[Codepen - WalterNascimentoBarroso](https://codepen.io)