refactor environment variable handling to prioritize .env values over PHP-FPM and improve dotenv loading logic
This commit is contained in:
21
common.php
21
common.php
@ -5,10 +5,21 @@
|
|||||||
require_once __DIR__ . '/lib/text_sanitize.php';
|
require_once __DIR__ . '/lib/text_sanitize.php';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read an environment variable (getenv, then $_ENV / $_SERVER).
|
* Values loaded from the project .env file (see qdb_load_dotenv).
|
||||||
* PHP-FPM often disables putenv(); .env is still loaded into $_ENV.
|
* Checked before getenv so a stale/wrong FPM pool variable cannot override .env.
|
||||||
|
*
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
$GLOBALS['qdb_dotenv'] = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read an environment variable (.env file first, then getenv / $_ENV / $_SERVER).
|
||||||
|
* PHP-FPM often disables putenv(); .env is applied via qdb_dotenv + $_ENV.
|
||||||
*/
|
*/
|
||||||
function qdb_env_get(string $name): ?string {
|
function qdb_env_get(string $name): ?string {
|
||||||
|
if (isset($GLOBALS['qdb_dotenv'][$name]) && $GLOBALS['qdb_dotenv'][$name] !== '') {
|
||||||
|
return $GLOBALS['qdb_dotenv'][$name];
|
||||||
|
}
|
||||||
$v = getenv($name);
|
$v = getenv($name);
|
||||||
if ($v !== false && $v !== '') {
|
if ($v !== false && $v !== '') {
|
||||||
return $v;
|
return $v;
|
||||||
@ -33,7 +44,7 @@ function qdb_env_set(string $name, string $value): void {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Load KEY=value pairs from .env in the project root.
|
* Load KEY=value pairs from .env in the project root.
|
||||||
* Does not override variables already set in the real environment.
|
* Values from the file take precedence over PHP-FPM / getenv for the same keys.
|
||||||
*/
|
*/
|
||||||
function qdb_load_dotenv(string $path): void {
|
function qdb_load_dotenv(string $path): void {
|
||||||
if (!is_readable($path)) {
|
if (!is_readable($path)) {
|
||||||
@ -64,9 +75,7 @@ function qdb_load_dotenv(string $path): void {
|
|||||||
$value = substr($value, 1, -1);
|
$value = substr($value, 1, -1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (qdb_env_get($name) !== null) {
|
$GLOBALS['qdb_dotenv'][$name] = $value;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
qdb_env_set($name, $value);
|
qdb_env_set($name, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user