rogerpence.com

A nerd's blog

Easily modify PHP .env files

Posted on: Tuesday, Dec 05, 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.

Examples:

Change a key value:

$filename = .env file name
$ef = new EnvFile($filename); 
$ef->addOrChangeKey('DB_DATABASE', 'ROSEY');
$ef->save();

Add a new key value:

$filename = .env file name
$ef = new EnvFile($filename); 
$ef->addOrChangeKey('GIT_HASH', $hash);
$ef->save();

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

$filename = .env file name
$ef = new EnvFile($filename);
$ef->read($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:

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']  
#### Discuss commands that use EnvFile here.

Comments

  • This is a comment


    Submitted by roger pence
    1 day ago

Add your comment

You email is never shared with anyone else.

© Copyright 2017 by Roger Pence. All rights reserved.