41 lines
1.1 KiB
PHP
41 lines
1.1 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Load the environment variables from the .env file.
|
|
*/
|
|
function env_load($filePath)
|
|
{
|
|
if (!file_exists($filePath)) throw new Exception("The .env file does not exist. (el)");
|
|
|
|
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
foreach ($lines as $line) {
|
|
$line = trim($line);
|
|
|
|
// Skip lines that are empty after trimming or are comments
|
|
if ($line === '' || str_starts_with($line, '#')) continue;
|
|
|
|
// Skip lines without an '=' character
|
|
if (strpos($line, '=') === false) continue;
|
|
|
|
[$name, $value] = explode('=', $line, 2);
|
|
|
|
$name = trim($name);
|
|
$value = trim($value, " \t\n\r\0\x0B\"'"); // Trim whitespace and quotes
|
|
|
|
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
|
|
putenv("$name=$value");
|
|
$_ENV[$name] = $value;
|
|
$_SERVER[$name] = $value;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* Retrieve an environment variable.
|
|
*/
|
|
function env($key, $default = null)
|
|
{
|
|
return $_ENV[$key] ?? $_SERVER[$key] ?? (getenv($key) ?: $default);
|
|
}
|