79 lines
3.3 KiB
PHP
79 lines
3.3 KiB
PHP
<?php
|
|
// api/config/database.php
|
|
|
|
mysqli_report(MYSQLI_REPORT_OFF);
|
|
|
|
if (!function_exists('loadDatabaseConfig')) {
|
|
function loadDatabaseConfig(): array {
|
|
// Load .env if exists (for local development)
|
|
$envFile = __DIR__ . '/.env';
|
|
if (file_exists($envFile)) {
|
|
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
foreach ($lines as $line) {
|
|
if (trim($line) === '' || strpos(trim($line), '#') === 0) continue;
|
|
$parts = explode('=', $line, 2);
|
|
if (count($parts) === 2) {
|
|
$name = trim($parts[0]);
|
|
$value = trim($parts[1]);
|
|
// Strip quotes if any
|
|
if (strlen($value) >= 2 && ($value[0] === '"' || $value[0] === "'") && $value[0] === $value[-1]) {
|
|
$value = substr($value, 1, -1);
|
|
}
|
|
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
|
|
putenv(sprintf('%s=%s', $name, $value));
|
|
$_ENV[$name] = $value;
|
|
$_SERVER[$name] = $value;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Use $_SERVER or $_ENV first as Coolify/Docker usually passes them there, fallback to getenv
|
|
$config = [
|
|
'host' => $_SERVER['DB_HOST'] ?? $_ENV['DB_HOST'] ?? getenv('DB_HOST') ?: '127.0.0.1',
|
|
'user' => $_SERVER['DB_USER'] ?? $_ENV['DB_USER'] ?? getenv('DB_USER') ?: 'root',
|
|
'pass' => $_SERVER['DB_PASS'] ?? $_ENV['DB_PASS'] ?? getenv('DB_PASS') ?: '',
|
|
'name' => $_SERVER['DB_NAME'] ?? $_ENV['DB_NAME'] ?? getenv('DB_NAME') ?: 'webgis_class',
|
|
'port' => (int)($_SERVER['DB_PORT'] ?? $_ENV['DB_PORT'] ?? getenv('DB_PORT') ?: 3306),
|
|
'charset' => $_SERVER['DB_CHARSET'] ?? $_ENV['DB_CHARSET'] ?? getenv('DB_CHARSET') ?: 'utf8mb4',
|
|
];
|
|
|
|
// Only allow local override if we are truly in a local environment
|
|
$localConfigFile = __DIR__ . '/webgis_class/api/config/database.local.php';
|
|
if (is_file($localConfigFile) && ($config['host'] === '127.0.0.1' || $config['host'] === 'localhost')) {
|
|
$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: ' . $conn->connect_error // Add actual error message for debugging
|
|
]);
|
|
exit;
|
|
}
|
|
$conn->set_charset(DB_CHARSET);
|
|
}
|
|
return $conn;
|
|
} |