What are the best practices for securely storing and accessing database credentials in PHP scripts?

To securely store and access database credentials in PHP scripts, it is recommended to store the credentials in a separate configuration file outside of the web root directory. This helps prevent unauthorized access to the credentials. Additionally, use environment variables or a secure key management service to store sensitive information and avoid hardcoding credentials directly in the PHP script.

// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');

// db_connection.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);
}