Skip to content
PHP Logo

How can one prevent the creation of duplicate sessions on a website to avoid impersonation by unauthorized users?

To prevent the creation of duplicate sessions on a website and avoid impersonation by unauthorized users, you can generate a unique token for each session and store it in a database. Before creating a new session, check if the token already exists in the database to ensure that only one session is active per user.

php
<?php
session_start();

// Generate a unique token for the session
$token = uniqid();

// Check if the token already exists in the database
// Replace 'your_db_connection' with your actual database connection
$existing_token = mysqli_query(your_db_connection, "SELECT token FROM sessions WHERE user_id = {$_SESSION['user_id']}")->fetch_assoc();

if (!$existing_token) {
    // Store the token in the database
    mysqli_query(your_db_connection, "INSERT INTO sessions (user_id, token) VALUES ({$_SESSION['user_id']}, '$token')");
} else {
    // Use the existing token for the session
    $token = $existing_token['token'];
}

// Set the session token
$_SESSION['token'] = $token;
?>