Skip to content

Instantly share code, notes, and snippets.

@philipborbon
Created July 5, 2019 05:44
Show Gist options
  • Save philipborbon/d2c87ad5192e93d8a03caf5109583e43 to your computer and use it in GitHub Desktop.
Save philipborbon/d2c87ad5192e93d8a03caf5109583e43 to your computer and use it in GitHub Desktop.
PHP .env Sample Implementation
<?php
/**
* Create .env file in same directory in following format
* DB_HOST=localhost
* DB_USERNAME=username
* DB_PASSWORD=password
*
*
* Usage:
*
* include 'path-to-env-autoload.php/env.autoload.php';
*
* $hostValue = env('DB_HOST', 'www.google.com');
*/
if( file_exists($file = dirname(__FILE__) . '/.env') ) {
foreach(explode(PHP_EOL, file_get_contents($file)) as $line) {
if( empty($line) ) continue;
list($key, $value) = explode("=", $line, 2);
putenv("$key=$value");
}
}
if( !function_exists('env') ) {
function env($key, $default = null){
$value = getenv($key);
if ($value === false) {
return $default;
}
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment