What are the best practices for handling database connections in PHP to avoid security vulnerabilities?
To avoid security vulnerabilities when handling database connections in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to store database credentials in a separate configuration file outside of the web root to prevent unauthorized access. Finally, always sanitize user input to prevent cross-site scripting attacks.
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>