What best practices should be followed when handling sensitive information such as database credentials in PHP scripts?
Sensitive information such as database credentials should never be hard-coded directly into PHP scripts, as this poses a security risk. Instead, it is recommended to store these credentials in a separate configuration file outside of the web root, and then include this file in your PHP scripts to access the credentials securely.
// config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database');
// database.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);
}