How to easily read or write PHP .env files
Posted on: Sunday, Dec 17, 2017
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.
EnvFile class has the following public members available:
__construct($filename). The constructor requires a fully qualified
addOrChangeKey($key, $newValue). Add or change a given key's value.
save(). Save the file to the file name used to read the
.envfile. All lines are written back out in their original order and blank lines and comments are persisted.
saveAsSample($keysToHide). Create a sample
.envfile named the same as the file name used to read the original
$keysToHideis an array of key names for which values should be hidden. Any hidden key value is written as
.envfile is safe for including in source control.
$filename = .env file name $ef = new EnvFile($filename); $ef->addOrChangeKey('DB_DATABASE', 'ROSEY'); $ef->save();
$filename = .env file name $ef = new EnvFile($filename); $ef->addOrChangeKey('GIT_HASH', $hash); $ef->save();
Create a sample
.env file obfuscating the
DB_PASSWORD key values.
$filename = .env file name $ef = new EnvFile($filename); $ef->read($filename); $ef->saveAsSample(['DB_DATABASE', 'DB_PASSWORD'])
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.
.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
nis the ordinal position of the placeholder) and the value is assigned '*BLANK.'
- For comment lines, the key is assigned '*COMMENTn' (where
nis 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:
APP_URL=http://localhost # Points to MariaDB DB_DATABASE=hal9000 DB_PASSWORD=ow$5eiRua
is serialized internally like this:
['APP_URL' => 'http://localhost', '*BLANK1' => '*BLANK', '*COMMENT2' => 'Points to MariaDB', 'DB_DATABASE' => 'hal9000', 'DB_PASSWORD' = > 'ow$5eiRua']