What best practices should be followed when handling database connections in PHP to avoid access denied errors?
When handling database connections in PHP, it's important to securely store and retrieve database credentials to avoid access denied errors. One best practice is to use environment variables to store sensitive information like database username and password, and then access these variables in your PHP script to establish the database connection.
<?php
// Set database credentials as environment variables
$host = getenv('DB_HOST');
$username = getenv('DB_USERNAME');
$password = getenv('DB_PASSWORD');
$database = getenv('DB_NAME');
// Create a database connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Related Questions
- What are the potential security risks associated with directly inserting user input into a MySQL query in PHP?
- What are the advantages of using a template engine for storing and executing PHP code?
- Are there any best practices for handling long strings in PHP to ensure proper formatting and readability?