-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.php
More file actions
48 lines (41 loc) · 1.63 KB
/
Copy pathdatabase.php
File metadata and controls
48 lines (41 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
// 1. Read and parse the local .env file line by line
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
// Skip comment lines
if (strpos(trim($line), '#') === 0) continue;
// Split each line by the first '=' character
list($name, $value) = explode('=', $line, 2);
$_ENV[trim($name)] = trim($value);
}
}
// 2. Extract database connection parameters from $_ENV
$host = $_ENV['DB_HOST'] ?? null;
$port = $_ENV['DB_PORT'] ?? null;
$db = $_ENV['DB_NAME'] ?? null;
$user = $_ENV['DB_USER'] ?? null;
$pass = $_ENV['DB_PASS'] ?? null;
if (!$host || !$port || !$db || !$user || !$pass) {
header('Content-Type: application/json', true, 500);
echo json_encode(["error" => "Critical server configuration error: Missing database environment variables."]);
exit;
}
// 3. Construct the Data Source Name (DSN) string
$dsn = "pgsql:host=$host;port=$port;dbname=$db;";
// 4. Set secure execution attributes for the PDO instance
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// 5. Instantiate the PDO object to establish the network socket connection
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
// If connection fails, catch the error and stop execution safely
header('Content-Type: application/json', true, 500);
echo json_encode(["error" => "Database connection failed: " . $e->getMessage()]);
exit;
}