Files
2026-08-07 03:24:19 +08:00

38 lines
1.2 KiB
PHP

<?php
function loadEnv($path) {
if (!is_readable($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;
if (strpos($line, '=') === false) continue;
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
if (strlen($value) >= 2 && $value[0] === '"' && substr($value, -1) === '"') {
$value = substr($value, 1, -1);
}
if ($key === '') continue;
putenv("$key=$value");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
loadEnv(__DIR__ . '/../.env');
$host = getenv("MYSQLHOST");
$db = getenv("MYSQLDATABASE");
$user = getenv("MYSQLUSER");
$pass = getenv("MYSQLPASSWORD");
$port = getenv("MYSQLPORT") ?: 3306;
try {
$pdo = new PDO("mysql:host=$host;dbname=$db;port=$port;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
?>