How can a login system be securely implemented in PHP?

To implement a secure login system in PHP, it is important to use password hashing to securely store user passwords in the database. Additionally, using prepared statements with parameterized queries can help prevent SQL injection attacks. Finally, implementing session management and CSRF protection can enhance the security of the login system.

// Secure login system implementation in PHP

// Start the session
session_start();

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate user input
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Connect to the database
    $conn = new mysqli("localhost", "username", "password", "database");

    // Prepare a SQL statement
    $stmt = $conn->prepare("SELECT id, username, password FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($id, $dbUsername, $dbPassword);
    $stmt->fetch();

    // Verify the password
    if (password_verify($password, $dbPassword)) {
        // Password is correct, set session variables
        $_SESSION["user_id"] = $id;
        $_SESSION["username"] = $dbUsername;
        // Redirect to the dashboard
        header("Location: dashboard.php");
        exit();
    } else {
        // Password is incorrect, display error message
        echo "Invalid username or password";
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
}