I think if it is without the use of frameworks, it is also considering not using external libraries, so you parse the .ini
with parse_ini_file
(which can actually have any extension) that is very similar , 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 true
:
$parsed = parse_ini_file('config/foo.env', true);
It 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 $_ENV
, Laravel uses it when the application does a requeste, adding the values of .env
, but I personally think this is optional, even if you want to do it 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 executing this, but I do not see much because using it further.
Another option that I think might even be a bit simpler, would be to 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 usage would look like this:
var_dump(MeuEnv('mysql_host'), MeuEnv('mysql_login'));
Recommendation
I really recommend that you do not allow such files to be publicly accessible, Laravel itself is safe in itself, but a lot of people instead of pointing to VirtualHost for the public
folder of it just move to public_html/public
or www/public
and create a .htaccess
that rewrites the URL, so far so good, it may not be externally accessible, but if .htaccess is misconfigured content:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Files will be exposed, this can occur in your project too, so I recommend you be careful about this and if possible keep your .env
out of the root folder of your server (usually public_html
, www
) and if you can also only allow the file reading and handling for the operating system user who actually tweaks these files, then never use permissions like 777
.