What are common methods for securely storing database connection credentials in PHP applications?
Storing database connection credentials securely in PHP applications is crucial to prevent unauthorized access to sensitive information. One common method is to store the credentials in a separate configuration file outside of the web root directory, and then include this file in your PHP scripts. Another approach is to use environment variables to store the credentials and access them in your PHP code.
// Method 1: Storing credentials in a separate configuration file
// config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');
// database.php
<?php
require_once 'config.php';
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Method 2: Using environment variables
$host = getenv('DB_HOST');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$name = getenv('DB_NAME');
$connection = new mysqli($host, $user, $pass, $name);