57 lines
2.1 KiB
PHP
57 lines
2.1 KiB
PHP
<?php
|
|
/**
|
|
* Load environment variables from a .env file.
|
|
* PHP 7.x compatible — no str_starts_with().
|
|
*/
|
|
if (!function_exists('loadEnv')) {
|
|
function loadEnv($path) {
|
|
if (!file_exists($path)) {
|
|
return;
|
|
}
|
|
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
if ($lines === false) return;
|
|
foreach ($lines as $line) {
|
|
$line = trim($line);
|
|
if ($line === '' || $line[0] === '#') {
|
|
continue;
|
|
}
|
|
$parts = explode('=', $line, 2);
|
|
if (count($parts) < 2) continue;
|
|
$key = trim($parts[0]);
|
|
$value = trim($parts[1]);
|
|
// Strip surrounding quotes if present
|
|
if (strlen($value) >= 2 && $value[0] === '"' && $value[strlen($value)-1] === '"') {
|
|
$value = substr($value, 1, -1);
|
|
}
|
|
if (!array_key_exists($key, $_ENV)) {
|
|
$_ENV[$key] = $value;
|
|
$_SERVER[$key] = $value;
|
|
// putenv() may be disabled on some shared hosts (e.g. InfinityFree)
|
|
if (function_exists('putenv')) {
|
|
putenv("$key=$value");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Try project root .env — works both locally and on InfinityFree
|
|
$envPath = __DIR__ . '/../.env';
|
|
loadEnv($envPath);
|
|
|
|
// Read env vars — prefer $_ENV (always populated) with getenv() fallback
|
|
$host = $_ENV['DB_HOST'] ?? getenv('DB_HOST') ?? '';
|
|
$ngalan = $_ENV['DB_USER'] ?? getenv('DB_USER') ?? '';
|
|
$sikreto = $_ENV['DB_PASS'] ?? getenv('DB_PASS') ?? '';
|
|
$deytabeys = $_ENV['DB_NAME'] ?? getenv('DB_NAME') ?? '';
|
|
|
|
if (empty($host) || empty($ngalan)) {
|
|
die('<p style="color:red;font-family:monospace;padding:20px">DB config missing. Please create a .env file from .env.example</p>');
|
|
}
|
|
|
|
$mysqli = new mysqli($host, $ngalan, $sikreto, $deytabeys);
|
|
|
|
if ($mysqli->connect_error) {
|
|
die('<p style="color:red;font-family:monospace;padding:20px">Connection failed: ' . htmlspecialchars($mysqli->connect_error) . '</p>');
|
|
}
|
|
?>
|