Files
Webgis-Class/api/config/database.php
T
Abimanyu Ridho 6c909dd168 update config
2026-06-11 18:50:04 +07:00

105 lines
3.3 KiB
PHP

<?php
// api/config/database.php
mysqli_report(MYSQLI_REPORT_OFF);
/**
* Parse and load a .env file into the environment.
* Supports KEY=VALUE format, ignores comments (#) and empty lines.
*/
if (!function_exists('loadEnvFile')) {
function loadEnvFile(string $filePath): void {
if (!is_file($filePath)) {
return;
}
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
// Skip comments and empty lines
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
// Split on first '=' only
$eqPos = strpos($line, '=');
if ($eqPos === false) {
continue;
}
$key = trim(substr($line, 0, $eqPos));
$value = trim(substr($line, $eqPos + 1));
// Strip surrounding quotes if present
if (
strlen($value) >= 2 &&
(($value[0] === '"' && $value[-1] === '"') ||
($value[0] === "'" && $value[-1] === "'"))
) {
$value = substr($value, 1, -1);
}
// Only set if not already defined by the server/environment
if ($key !== '' && getenv($key) === false) {
putenv("$key=$value");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}
}
// Load .env from project root (two levels up from this file)
loadEnvFile(dirname(__DIR__, 2) . '/.env');
if (!function_exists('loadDatabaseConfig')) {
function loadDatabaseConfig(): array {
$config = [
'host' => getenv('DB_HOST') ?: 'localhost',
'user' => getenv('DB_USER') ?: 'root',
'pass' => getenv('DB_PASS') ?: '',
'name' => getenv('DB_NAME') ?: 'webgis_class',
'port' => (int)(getenv('DB_PORT') ?: 3306),
'charset' => getenv('DB_CHARSET') ?: 'utf8mb4',
];
// Allow local override file for development (not committed to git)
$localConfigFile = __DIR__ . '/database.local.php';
if (is_file($localConfigFile)) {
$localConfig = require $localConfigFile;
if (is_array($localConfig)) {
$config = array_merge($config, array_intersect_key($localConfig, $config));
}
}
return $config;
}
}
$dbConfig = loadDatabaseConfig();
define('DB_HOST', $dbConfig['host']);
define('DB_USER', $dbConfig['user']);
define('DB_PASS', $dbConfig['pass']);
define('DB_NAME', $dbConfig['name']);
define('DB_PORT', $dbConfig['port']);
define('DB_CHARSET', $dbConfig['charset']);
function getDB(): mysqli {
static $conn = null;
if ($conn === null) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);
if ($conn->connect_error) {
error_log('DB connection failed: ' . $conn->connect_error);
http_response_code(500);
echo json_encode([
'status' => 'error',
'message' => 'Koneksi database gagal'
]);
exit;
}
$conn->set_charset(DB_CHARSET);
}
return $conn;
}