feat(security): support outside-webroot .env loading from /home/urukprize/.env

This commit is contained in:
Hamza-Ayed
2026-09-18 17:59:45 +03:00
parent d8ef078c52
commit 6817ce5ee3
2 changed files with 21 additions and 13 deletions
-1
View File
@@ -14,6 +14,5 @@ return [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
],
];
+21 -12
View File
@@ -32,21 +32,30 @@ if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
});
}
// 2. Load Environment Variables if Dotenv exists or read .env manually
$envFile = __DIR__ . '/../.env';
if (file_exists($envFile)) {
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (str_starts_with(trim($line), '#') || !str_contains($line, '=')) {
continue;
}
[$name, $val] = explode('=', $line, 2);
$name = trim($name);
$val = trim($val, " \t\n\r\0\x0B\"'");
if (!getenv($name)) {
// 2. Multi-Path Secure Environment Loader (Prioritizes Outside-Webroot .env on CloudPanel)
$envCandidates = [
'/home/urukprize/.env', // 1. Production outside webroot on CloudPanel
dirname(__DIR__, 4) . '/.env', // 2. Dynamic 4-levels up from backend/public
dirname(__DIR__, 2) . '/.env', // 3. Project root on Mac local dev (/uruk-prize/.env)
dirname(__DIR__, 1) . '/.env', // 4. Decoy / fallback inside backend
];
foreach ($envCandidates as $candidate) {
if (file_exists($candidate) && is_readable($candidate) && filesize($candidate) > 0) {
$lines = file($candidate, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if (str_starts_with($line, '#') || !str_contains($line, '=')) {
continue;
}
[$name, $val] = explode('=', $line, 2);
$name = trim($name);
$val = trim($val, " \t\n\r\0\x0B\"'");
putenv("$name=$val");
$_ENV[$name] = $val;
$_SERVER[$name] = $val;
}
break; // Successfully loaded highest-priority environment file
}
}