Hardening Database Connections and Managing Configuration Files
The provided config.php script suffers from several critical security flaws that make it unsuitable for any production environment. The primary issue is the hardcoded credentials embedded directly in the source code. Storing database usernames, passwords, and connection strings in plain text within a file included by your application creates an immediate attack vector. If an attacker gains read access to your web root, they can instantly extract these secrets without needing to reverse-engineer an encrypted vault or hunt for environment variables.
Furthermore, the script relies on the mysql_connect function, which is deprecated and removed in PHP 7.0+. This legacy API lacks support for prepared statements, making it impossible to prevent SQL injection attacks at the connection level. While SQL injection is primarily mitigated during query execution, using modern drivers ensures access to features like SSL verification, which is essential for encrypting data in transit between your application and the database server.
Moving Credentials to Environment Variables
The industry standard for managing sensitive configuration data is to externalize it from the codebase entirely. You should never check a file containing raw passwords into version control systems like Git. Instead, store these values in environment variables.
On Linux or macOS, you can create an .env file in your project root:
DB_HOST=localhost
DB_USERNAME=root
DB_PASSWORD=your_secure_password_here
DB_DATABASE=practise
In your config.php, load these values using the getenv() function. This ensures that the credentials are only present in memory during execution and are never written to disk as plain text alongside your source code:
<?php
$host = getenv('DB_HOST') ?: 'localhost';
$username = getenv('DB_USERNAME');
$password = getenv('DB_PASSWORD');
$database = getenv('DB_DATABASE');
// Fail fast if a critical credential is missing
if (empty($username) || empty($password)) {
die("Database credentials are not configured. Check your environment variables.");
}
?>
Switching to PDO for Modern Security
You must abandon the mysql_* functions in favor of the PHP Data Objects (PDO) extension or the MySQLi extension with prepared statements. PDO provides a unified interface and, crucially, supports database-specific drivers that handle SSL connections natively.
Here is how you would refactor your connection logic using PDO to ensure a secure connection:
<?php
// Define DSN, username, and password
$host = getenv('DB_HOST') ?: 'localhost';
$username = getenv('DB_USERNAME');
$password = getenv('DB_PASSWORD');
$database = getenv('DB_DATABASE');
// Construct the DSN.
// Note: Adding "sslmode=require" or similar flags depends on your specific driver and version.
$dsn = "mysql:host=$host;dbname=$database;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Set default fetch mode
PDO::ATTR_EMULATE_PREPARES => false, // Disable emulation for real security
];
try {
// Establish the connection
$pdo = new PDO($dsn, $username, $password, $options);
echo "Database connection successful.";
} catch (PDOException $e) {
// Log the full error to server logs, not to the browser
error_log($e->getMessage());
echo "Database connection failed. Please check your configuration.";
}
?>
Handling Configuration in Laravel Projects
If you are building a modern PHP application using the Laravel framework, the approach is slightly different but equally important. Laravel handles this out of the box with robust abstraction and security best practices built into its core.
Instead of manually editing config.php or config/database.php, you should rely on Laravel's configuration management system. The framework provides a dedicated .env file specifically for storing environment variables, and it includes a secure encryption feature to encrypt specific config values directly in the file if needed.
For example, you can define your database credentials in the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=practise
DB_USERNAME=root
DB_PASSWORD=secret_key
Laravel will automatically load these values into your config/database.php configuration file at runtime, ensuring they are never hardcoded in the source code you commit to a repository. For more details on managing these secure configurations within an artisan-based project, refer to the resources available at https://laravelcompany.com.
Final Recommendations
To summarize the necessary changes: stop using mysql_connect, eliminate hardcoded passwords from your source code, and migrate to environment variables loaded via getenv(). If you are starting a new project or refactoring an existing one, adopt PDO with exception handling. These steps ensure that your database connection is resilient against credential theft and adheres to modern PHP standards.