Skip to content

Loads environmental variables from a .env file.

Notifications You must be signed in to change notification settings

wpscholar/phpdotenv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP dotenv

A .env file parsing and loading library for PHP.

Automatically loads variables into a number of contexts:

  • getenv() (default)
  • $_ENV (default)
  • $_SERVER (default)
  • apache_getenv (optional)
  • PHP constants (optional)
  • Global variables (optional)
  • A custom config array (optional)

Why?

You should never store sensitive credentials in your code. Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments – such as database credentials or credentials for 3rd party services – should be extracted from the code into environment variables.

Requirements

  • PHP 5.4

Installation

Using Composer, run composer require wpscholar/phpdotenv.

Make sure you have a line in your code to handle autoloading:

<?php

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

Usage

Create a new loader and use any of the available methods to help customize your configuration:

<?php

$loader = new wpscholar\phpdotenv\Loader(); // Can also do wpscholar\phpdotenv\Loader::create() 
$loader
    ->config([ // Must be used to customize adapters, can also be used to set defaults or required variables.
        'adapters' => [
            'apache',   // Uses apache_setenv() 
            'array',    // Uses a custom array
            'define',   // Uses define() to set PHP constants
            'env',      // Uses $_ENV
            'global',   // Sets global variables
            'putenv',   // Uses putenv()
            'server'    // Uses $_SERVER
        ], 
        'defaults' => [
            'foo' => 'bar' // Set a default value if not provided in .env  	
        ],
        'required' => [
            'bar', // Require that a variable be defined in the .env file. Throws an exception if not defined.
            'baz',
        ],
    ])
    ->required([ // Another way to define required variables
        'bar',
        'baz',
        'quux',    	
    ])
    ->setDefaults([ // Another way to set defaults
        'foo' => 'bar',	
    ])
    ->parse([ __DIR__ . '/.env', dirname( __DIR__ ) . '/.env' ]) // Array of file paths to check for a .env file. Parses found file and loads vars into memory.
    ->set( 'qux', $loader->get('foo') ); // Override variables after loading, but with access to existing variables before they are loaded into the environment.
    
// Validate variable values after parsing the .env file, but before loading the results into the environment.
$loader->validate('foo')->notEmpty();
$loader->validate('bar')->isBoolean();
$loader->validate('baz')->isInteger();
$loader->validate('qux')->notEmpty()->allowedValues( [ 'bar', 'baz' ] ); // Validations can be chained together.
$loader->validate('quux')->assert(function( $value ) { // Apply your own custom validation assertions.
    return is_int($value) && $value > 0 && $value <= 10;	
});

// Call load() to load variables into the environment without overwriting existing variables.
$loader->load();

// Call overload() to load variables into the environment, overwriting any existing variables.
$loader->overload();

It is possible to create multiple instances of the loader, each loading a different .env file and loading variables into different contexts.

Custom Configuration Array Example Usage

<?php

$loader = wpscholar\phpdotenv\Loader::create();
$loader
    ->config([ 'adapters' => 'array'] ) // All values are self-contained in an array within the loader.
    ->required([ 'bar', 'baz', 'quux', ])
    ->setDefaults([ 'foo' => 'bar' ])
    ->parse( __DIR__ . '/.env' )
    ->set( 'qux', $loader->get('foo') )
    ->load();

$config = $loader->all(); // Get an array containing the final values.

$bar = $loader->get('bar'); // Get a single value.

WordPress wp-config.php Example Usage