How to easily read or write PHP .env files

Posted on: Sunday, Dec 17, 2017

EnvFile class

The EnvFile class provides the ability to easily change and add .env file keys as well as create a sample .env file with obfuscated key values. EnvFile's code is available here.

The EnvFile class has the following public members available:

  • __construct($filename). The constructor requires a fully qualified .env file name.
  • addOrChangeKey($key, $newValue). Add or change a given key's value.
  • save(). Save the file to the file name used to read the .env file. All lines are written back out in their original order and blank lines and comments are persisted.
  • saveAsSample($keysToHide). Create a sample .env file named the same as the file name used to read the original .env file plus .app.sample. $keysToHide is an array of key names for which values should be hidden. Any hidden key value is written as ###. This sample .env file is safe for including in source control.
Change a key value:
$filename = .env file name
$ef = new EnvFile($filename); 
$ef->addOrChangeKey('DB_DATABASE', 'ROSEY');
Add a key value (if a key doesn't exist it is added, this code is the same code used to change a key value):
$filename = .env file name
$ef = new EnvFile($filename); 
$ef->addOrChangeKey('GIT_HASH', $hash);

Create a sample .env file obfuscating the DB_DATABASE and DB_PASSWORD key values.

$filename = .env file name
$ef = new EnvFile($filename);
$ef->saveAsSample(['DB_DATABASE', 'DB_PASSWORD'])

Implementation detail

EnvFile's constructor takes a fully qualified .env file as its single argument. The constructor calls the private read() method to read the .env file specified and serialize it to an internal associative array.

For .env file value pairs, the key and value comprises an array element. For comment and blank lines, two special key values are used:

  • For blank lines, the key is assigned '*BLANKn' (where n is the ordinal position of the placeholder) and the value is assigned '*BLANK.'
  • For comment lines, the key is assigned '*COMMENTn' (where n is the ordinal position of the placeholder) and the value is assigned the original contents of the line less its leading #.

The special key values' ordinal positions are used to ensure unique special key values.

For example, the following .env file fragment:


# Points to MariaDB

is serialized internally like this:

['APP_URL' => 'http://localhost',
 '*BLANK1' => '*BLANK',
 '*COMMENT2' => 'Points to MariaDB',
 'DB_DATABASE' => 'hal9000',
 'DB_PASSWORD' = > 'ow$5eiRua']  
#### Discuss commands that use EnvFile here.


  • Ператки для защиты рук Wally Plastic - товар поставляется прямым поставщиком от фабрики в Китае. Отправляем любой транспортной компанией. Тел: +79147116482 Дмитрий

    Submitted by MSCbor
    11 months ago
  • Транспортная логистическая компания "Азия-Трейдинг" оказывает услуги по доставке сборных и контейнерных грузов из Китая, Кореи и Японии под ключ.

    Submitted by MSCCymn
    10 months ago
  • Постоянно стремимся к улучшению сервиса и качества работы при внешнеторговых сделках с Китаем. Оказываем комплексные услуги по прямым поставкам товаров из КНР, организовываем доставку товара до склада в России.

    Submitted by
    9 months ago

Add your comment
You email is never shared with anyone else.

© Copyright 2017 by Roger Pence. All rights reserved.