Are there potential security risks in storing passwords in PHP scripts for database connections?
Storing passwords directly in PHP scripts for database connections poses a security risk because if an attacker gains access to the codebase, they can easily see the password. To mitigate this risk, it is recommended to store passwords in a separate configuration file outside of the web root directory. This way, even if the codebase is compromised, the passwords remain secure.
// config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');
?>
// db_connection.php
<?php
require_once('config.php');
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>