PHP Database Configuration with .env for Secure Credential Management

A .env file in PHP helps to secure sensitive information.
It stores database credentials and API keys safely.
It allows easy configuration of the application in different environments.
PHP Database Configuration with .env for Secure Credential Management
🔒 Benefits of Using .env
✅ Security: Keeps sensitive credentials out of your code.
🔄 Flexibility: Easily switch between development, testing, and production environments.
⚡ Simplicity: No need to modify code when moving projects between servers.
1️⃣ Create a .env File
Place the .env file outside your project root directory to keep it secure.
For example, you can create the .env file in a directory like C:/xampp/env-files/.
This will keep your credentials safe, as they won’t be publicly accessible.
.env
DB_HOST=localhost
DB_NAME=testdb
DB_USER=root
DB_PASS=secret
2️⃣ Create a Function to Read .env File
Since you are not installing dotenv, you need a function to manually load .env variables.
Create a config.php file and add this code:
Config.php
<?php
// Load environment variables from .env file
function loadEnv(string $filePath): void
{
if (!file_exists($filePath)) {
die("Error: .env file not found!");
}
//Reads all lines of .env and stores them in an array.
//Skips empty lines to avoid errors.
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
//Trims spaces and checks if the line starts with # (comment).
// If it's a comment, it skips to the next line.
if (strpos(trim($line), '#') === 0) {
continue; // Skip comments
}
// Splits each line into two parts: name=value
list($name, $value) = explode('=', $line, 2);
//Example
//DB_HOST=localhost
//DB_NAME=my_database
// 🔄 After explode():
//$name = "DB_HOST", $value = "localhost"
//$name = "DB_NAME", $value = "my_database"
// Limit to 2 parts in case value contains "="
//The 2 limit ensures it only splits at the first = (in case the value contains =).
$_ENV[trim($name)] = trim($value); // Store variables in $_ENV
//Stores the key-value pair in the $_ENV superglobal.
//$_ENV['DB_HOST'] = 'localhost';
//$_ENV['DB_NAME'] = 'my_database';
}
}
// Call the function to load .env variables
loadEnv(__DIR__ . '/.env');
//causes -> 403 Forbidden
/*
define('DB_HOST', $_ENV['DB_HOST'] ?? 'localhost'); // Default to localhost if not set
define('DB_NAME', $_ENV['DB_NAME'] ?? ''); // Consider setting a default or throwing an error
define('DB_USER', $_ENV['DB_USER'] ?? 'root'); // Default to root if not set
define('DB_PASS', $_ENV['DB_PASS'] ?? ''); // Keep empty if it is ""
*/
// Example usage (remove or comment out in production)
// echo "DB Host: " . DB_HOST . PHP_EOL;
// echo "DB Name: " . DB_NAME . PHP_EOL;
// echo "DB User: " . DB_USER . PHP_EOL;
// echo "DB Pass: " . DB_PASS . PHP_EOL;
?>
4️⃣ Test if .env Variables Work
Create a test.php file and check if the .env variables are loaded:
test.php
<?php
require_once 'Config.php';
echo "DB Host: " . DB_HOST . "<br>";
echo "DB Name: " . DB_NAME . "<br>";
echo "DB User: " . DB_USER . "<br>";
echo "DB Pass: " . DB_PASS . "<br>";
?>
If everything is correct, you should see your .env variables displayed on the screen. ✅
5️⃣ Important: Add .env to .gitignore
To protect your sensitive data, make sure to add .env to .gitignore so it doesn’t get uploaded to GitHub:
# Ignore .env file
.env