How can PHP be used to create a secure login system with database integration?

To create a secure login system with database integration in PHP, you can use techniques like password hashing, prepared statements to prevent SQL injection, and session management for user authentication. By implementing these security measures, you can protect user data and prevent unauthorized access to the system.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Validate user login credentials
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password'])) {
    // Start a session and store user information
    session_start();
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    header("Location: dashboard.php");
} else {
    echo "Invalid username or password";
}

$stmt->close();
$conn->close();
?>