pencil_automator/env_loader.php

55 lines
1.3 KiB
PHP

<?php
/**
* Environment Variable Loader
* Parses .env file and sets environment variables
*/
function loadEnvFile($path = null) {
// Default to .env file in same directory
$path = $path ?? __DIR__ . '/.env';
// Check if .env file exists
if (!file_exists($path)) {
error_log("Warning: .env file not found at: $path");
return false;
}
// Read file line by line
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
error_log("Error: Could not read .env file at: $path");
return false;
}
foreach ($lines as $line) {
// Skip comments
if (strpos(trim($line), '#') === 0) {
continue;
}
// Parse KEY=VALUE format
if (strpos($line, '=') !== false) {
list($key, $value) = explode('=', $line, 2);
// Trim whitespace
$key = trim($key);
$value = trim($value);
// Remove surrounding quotes if present
if (preg_match('/^(["\'])(.*)\\1$/', $value, $matches)) {
$value = $matches[2];
}
// Set environment variable
putenv("$key=$value");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
return true;
}
// Auto-load .env on include
loadEnvFile();