What are the common methods used for user authentication in PHP applications, and how can developers ensure the security of login systems?

Issue: User authentication is a critical aspect of web applications to ensure that only authorized users can access certain features or data. Common methods for user authentication in PHP applications include using session variables, cookies, and database queries to verify user credentials. To ensure the security of login systems, developers should implement measures such as password hashing, salting, and using prepared statements to prevent SQL injection attacks.

// Example of secure user authentication in PHP using password hashing and prepared statements

// Retrieve user input from login form
$username = $_POST['username'];
$password = $_POST['password'];

// Query the database to retrieve the hashed password for the given username
$stmt = $pdo->prepare("SELECT password FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

// Verify the password using password_verify function
if ($user && password_verify($password, $user['password'])) {
    // Password is correct, set session variables for authentication
    $_SESSION['logged_in'] = true;
    $_SESSION['username'] = $username;
    // Redirect to the dashboard or home page
    header('Location: dashboard.php');
    exit();
} else {
    // Invalid credentials, redirect back to the login page with an error message
    header('Location: login.php?error=1');
    exit();
}