What are the potential security risks of hard-coding credentials in PHP code?

Hard-coding credentials in PHP code can pose a significant security risk as it exposes sensitive information, such as usernames and passwords, directly in the source code. If an attacker gains access to the codebase, they can easily extract these credentials and potentially compromise the system. To mitigate this risk, it is recommended to store credentials in a secure configuration file outside of the web root directory and use environment variables or a secure key management service to access them in the code.

// config.php file outside of web root directory
define('DB_HOST', 'localhost');
define('DB_USER', getenv('DB_USER'));
define('DB_PASS', getenv('DB_PASS'));
define('DB_NAME', 'database_name');

// index.php file
require_once('config.php');

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);