I believe that if it is without the use of frameworks, you are also considering not using external libraries. So, you parse the .ini with parse_ini_file (which may actually have any extension) which is similar good, for example:
$parsed = parse_ini_file('config/foo.env');
If the contents of the file are:
; Comentários começam com ';'
[database]
mysql_host = foo.com
mysql_login = baz
mysql_pass = foobarbaz
[debug]
enable = false
error_level = 32767 ; = E_ALL
[requirements]
phpversion[] = "5.6"
phpversion[] = "7.0"
phpversion[] = "7.1"
phpversion[] = "7.2"
It will generate this (without the "sessions"):
Array
(
[mysql_host] => foo.com
[mysql_login] => baz
[mysql_pass] => foobarbaz
[enable] => 0
[error_level] => 32767
[phpversion] => Array
(
[0] => 5.6
[1] => 7.0
[2] => 7.1
[3] => 7.2
)
)
If you want to use the sessions add the true:
$parsed = parse_ini_file('config/foo.env', true);
Will generate this:
Array
(
[database] => Array
(
[mysql_host] => foo.com
[mysql_login] => baz
[mysql_pass] => foobarbaz
)
[debug] => Array
(
[enable] => 0
[error_level] => 32767
)
[requirements] => Array
(
[phpversion] => Array
(
[0] => 5.0
[1] => 5.1
[2] => 5.2
[3] => 5.3
)
)
)
Of course it is not mandatory to use the $_ENV, Laravel uses when the application makes a request, adding the values of the .env, but I personally think that this is optional, yet if you wish to make can use this way:
$envs = parse_ini_file('config/foo.env');
foreach ($envs as $key => $value) {
$_ENV[$key] = $value;
}
Of course it will only be available within the main script and after running it, but I don’t see much why use beyond this.
Another option that I think might even be a little simpler, would just use a function:
function MeuEnv($chave)
{
static $envs;
if (!$envs) {
$envs = parse_ini_file('config/foo.env');
}
return empty($envs[$chave]) ? null : $envs[$chave];
}
And the use would look like this:
var_dump(MeuEnv('mysql_host'), MeuEnv('mysql_login'));
Recommending
I really recommend that you don’t allow files like this to be publicly accessible, Laravel himself is safe in itself, but a lot of people instead of pointing to Virtualhost to the folder public of it just move to public_html/public or www/public and create a .htaccess rewriting the URL, so far so good, maybe not accessible externally, but if . htaccess is poorly configured content this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
The files will be exposed, this can occur in your project as well, so I recommend you to be careful with this and if possible keep yours .env outside your server’s root folder (usually public_html, www) and if you can also only allow file reading and handling to the operating system user who actually tweak these files, then never use permissions like 777.
getenv()would be the correct function name.– Ivan Ferrer