Skip to content

Instantly share code, notes, and snippets.

@brandonkramer
Last active January 31, 2022 11:37
Show Gist options
  • Save brandonkramer/81939c8d528ab0e6cc763ec74d74e8d1 to your computer and use it in GitHub Desktop.
Save brandonkramer/81939c8d528ab0e6cc763ec74d74e8d1 to your computer and use it in GitHub Desktop.
PHP read .env file into an readable array to load system environment configuration $_ENV, $_SERVER, env, dotenv, getenv
<?php
try {
/**
* Throw exception if not found or is unreadable
*/
if ( !file_exists( __DIR__ . '/.env' ) || !is_readable( __DIR__ . '/.env' ) ) {
throw new Exception( 'The .env file is not found or unreadable.' );
}
/**
* Get the .env file, ignore new and empty lines.
*/
$_ENV = file( __DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
/**
* Check if we are dealing with an array
*/
if ( is_array( $_ENV ) ) {
/**
* Catch settings and create an readable array
*/
$_ENV = array_column( array_map( function ( $_ENV_VAR ) {
if ( substr( $_ENV_VAR, 0, 1 ) !== '#' && strpos( $_ENV_VAR, '=' ) !== false ) {
list( $key, $value ) = explode( '=', trim( $_ENV_VAR ), 2 );
return [ $key, $value ];
}
}, $_ENV ), 1, 0 );
} else throw new Exception( 'The .env file is not found or unreadable.' );
/**
* Handle exceptions
*/
} catch ( Exception $e ) {
echo $e->getMessage();
} finally {
/**
* Globalize environment settings array
*/
global $_ENV;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment