What are the risks associated with directly including database connection details in PHP scripts, and how can this be improved?
Including database connection details directly in PHP scripts can pose a security risk as it exposes sensitive information such as usernames and passwords. This can lead to unauthorized access to the database if the script is compromised. To improve this, a common practice is to store the connection details in a separate configuration file outside of the web root directory and include this file in the PHP scripts that require database access.
<?php
// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');
// db.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);
}