What are the best practices for handling database credentials in PHP scripts?
Storing database credentials directly in PHP scripts can pose a security risk as they can be easily accessed if the script is compromised. To mitigate this risk, it is recommended to store credentials in a separate configuration file outside of the web root directory and restrict access to it. This way, even if the PHP script is accessed, the credentials remain secure.
// config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');
```
```php
// database_connection.php
<?php
require_once('config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}