Files
mivo/app/Core/Env.php

49 lines
1.4 KiB
PHP

<?php
namespace App\Core;
class Env {
/**
* Load environment variables from .env file
*
* @param string $path Path to .env file
* @return void
*/
public static function load($path) {
if (!file_exists($path)) {
return;
}
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
// Ignore comments
if (strpos(trim($line), '#') === 0) {
continue;
}
// Parse KEY=VALUE
if (strpos($line, '=') !== false) {
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Handle quoted strings
if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
$value = substr($value, 1, -1);
} elseif (str_starts_with($value, "'") && str_ends_with($value, "'")) {
$value = substr($value, 1, -1);
}
if (!array_key_exists($key, $_SERVER) && !array_key_exists($key, $_ENV)) {
putenv(sprintf('%s=%s', $key, $value));
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}
}
}