Skip to content

Instantly share code, notes, and snippets.

@amoslanka
Forked from eric1234/README.md
Last active December 23, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amoslanka/6691507 to your computer and use it in GitHub Desktop.
Save amoslanka/6691507 to your computer and use it in GitHub Desktop.

Forked from https://gist.github.com/eric1234/5628416

Adjustments:

  • No environment based .env filenames
  • No need for APP_ENV

Purpose

Somewhat like dotenv but for PHP.

The goals is to remove all config scattered about in files and have one authoritative source for that config info. Searches for .env up the directory tree until it gets to DOCUMENT_ROOT.

Usage

Create a .env file in the root of your website. In that file put all configuration. Example:

DB_DSN=mysql:dbname=mydb;host=myhost
DB_USERNAME=myuser
DB_PASSWORD=mypass

Then in your code you can simply access these values via the $_ENV global.

<?php
namespace Env;
$env = ".env";
$cur = realpath(__DIR__);
$root = realpath($_SERVER['DOCUMENT_ROOT']);
$found = false;
while( !$found && strpos($cur, $root) == 0 ) {
$file = null;
if( file_exists("$cur/$env") ) $file = "$cur/$env";
if( file_exists("$cur/environments/$env") ) $file = "$cur/environments/$env";
if( $file ) {
foreach(explode("\n", file_get_contents($file)) as $line) {
if( empty($line) ) continue;
list($var, $val) = explode("=", $line, 2);
$_ENV[$var] = $val;
}
$found = true;
}
$cur = dirname($cur);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment