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);
}
Keywords
Related Questions
- How can you retrieve and include the IP address of the user accessing a PHP page in an email?
- How can arrays be effectively used in PHP to map numerical values to corresponding text labels?
- When should sorting of data be done - in SQL, PHP, or JavaScript - for optimal performance in a web application?