How can PHP developers establish and maintain a secure database connection in their scripts?
To establish and maintain a secure database connection in PHP scripts, developers should use the PDO (PHP Data Objects) extension with prepared statements to prevent SQL injection attacks. They should also store database connection details in a separate configuration file outside the web root directory to prevent unauthorized access. Additionally, developers should regularly update their PHP and database software to patch any security vulnerabilities.
<?php
// Database configuration
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
// Establish a secure database connection
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>