What are the security considerations when establishing and maintaining database connections in PHP scripts that handle sensitive data?
When handling sensitive data in PHP scripts, it is crucial to ensure secure database connections to prevent unauthorized access. One way to enhance security is by using parameterized queries to prevent SQL injection attacks. Additionally, encrypting sensitive data before storing it in the database can add an extra layer of protection.
<?php
// Establishing a secure database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Using parameterized queries to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
// Encrypting sensitive data before storing in the database
$encrypted_data = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
$stmt = $conn->prepare("INSERT INTO sensitive_data (data) VALUES (?)");
$stmt->bind_param("s", $encrypted_data);
$stmt->execute();
// Close connection
$conn->close();
?>
Related Questions
- What best practices should be followed when defining and using variables for Captcha validation in PHP?
- What is the correct way to include a file in PHP using the include function?
- What best practices should be followed when using JavaScript functions in PHP to handle window opening from database results?