What potential security risks are involved in using file-based login credentials in PHP?

Using file-based login credentials in PHP can pose security risks such as exposing sensitive information if the file is not properly secured, allowing unauthorized access if the file is accessed by malicious users, and making it difficult to manage and update credentials securely. To mitigate these risks, it is recommended to store login credentials securely in a database with proper encryption techniques.

// Sample PHP code snippet for securely storing login credentials in a database

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Securely store login credentials
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Hash the password before storing it in the database
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Insert the credentials into the database
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the database connection
$conn->close();