What are best practices for handling IP address and username comparisons in PHP to prevent duplicate logins?

To prevent duplicate logins based on IP address and username comparisons in PHP, you can store the IP address and username of each logged-in user in a database table. When a user attempts to log in, you can check if there is already a record in the table with the same IP address and username combination. If a match is found, you can prevent the user from logging in again to avoid duplicate logins.

// Assuming you have a database connection established

// Check if there is already a record with the same IP address and username
$stmt = $pdo->prepare("SELECT * FROM logged_in_users WHERE ip_address = ? AND username = ?");
$stmt->execute([$user_ip, $username]);
$existing_user = $stmt->fetch();

if($existing_user) {
    // Prevent the user from logging in again
    echo "User is already logged in.";
    exit;
} else {
    // Allow the user to log in and store their IP address and username in the database
    $insert_stmt = $pdo->prepare("INSERT INTO logged_in_users (ip_address, username) VALUES (?, ?)");
    $insert_stmt->execute([$user_ip, $username]);
}