-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv_loader.php
More file actions
45 lines (38 loc) · 1.27 KB
/
Copy pathenv_loader.php
File metadata and controls
45 lines (38 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/**
* Simple .env loader. Parses KEY=VALUE pairs and stores them in environment.
*/
if (!function_exists('loadEnv')) {
function loadEnv(string $filePath, bool $overwrite = false): void
{
if (!is_file($filePath) || !is_readable($filePath)) {
return;
}
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
return;
}
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) {
continue;
}
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
if ($key === '') {
continue;
}
if ((str_starts_with($value, '"') && str_ends_with($value, '"')) || (str_starts_with($value, "'") && str_ends_with($value, "'"))) {
$value = substr($value, 1, -1);
}
$current = getenv($key);
if ($current !== false && !$overwrite) {
continue;
}
putenv(sprintf('%s=%s', $key, $value));
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}