What is the best practice for securely handling database connection details in PHP applications?

Storing database connection details, such as usernames and passwords, directly in PHP code can pose a security risk if the code is exposed or compromised. To securely handle database connection details in PHP applications, it is recommended to store these sensitive information in a separate configuration file outside of the web root directory and use PHP constants to access them in the application code.

<?php
// 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);
}