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.


  • Оптовая продажа карьерных шин 315 80 R22.5 для грузовой техники по ценам производителя <a href=>Shandong HAOHUA Tire Co., Ltd.</a>

    Submitted by Mish
    1 month ago

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

© Copyright 2017 by Roger Pence. All rights reserved.