Al.G.
Al.G.

Reputation: 4387

Prevent session from being used by multiple users

The first time a user visits my site a session is created where I store their IP address and their user agent. If these exist in my DB, I use their id, otherwise I insert them and use PDO->lastInsertId

Problem is - can I trust php that a session is being used only by one IP address and one user agent?

This is how $_SESSION['ip'] looks like:

array(2) {
  ["id"]=>
  string(1) "1" /* row id in the table */
  ["full"]=>
  string(99) "Mozilla/5.0 bla-bla"
}

Basically this is what I'm doing:

if(isset($_SESSION['ip'])) {
    if($_SESSION['ip']['full'] === $ip)
        return $_SESSION['ip']['id'];
    session_destroy();
    session_start();
}
$ipId = query('SELECT id FROM ip_addresses WHERE ip=$ip');
// yes, prepared statements are used

if(!$ipId) {
    query('INSERT INTO ip_addresses (ip) VALUES ($ip)');
    $ipId = lastInsertId();
}
$_SESSION['ip'] = ['id'   => $ipId,
                   'full' => $ip ];

My idea is to prevent one session being used by multiple users.
Is this code OK or I can remove this check?

Here you can find the full code - http://pastebin.com/VFVJxTW5

Upvotes: 0

Views: 1003

Answers (2)

dbrumann
dbrumann

Reputation: 17166

Your PHP-session and your IP-address are pretty much unrelated. There are few examples which may make it clear. You can use multiple browsers on the same PC with each having their own (different) session. Also for example when you are accessing your website from a home network that is connected to the internet via a router they usually share the same (outbound) IP-address - that of the router being connected to the internet via your ISP. This means even multiple users on different devices can have different sessions on your website.

In all these scenarios PHP will generate a new session_id or use an existing one based on whether the request already contains a session id or not. With older PHP-versions it was sometimes quite common to add the session id to the url as a parameter, there it was easy to see as part of the URL. This is obviously a bad idea, since everyone knowing the URL can hijack the session. But you could easily see, which session was used in the URL (which is also what made it bad).

So how to make sure only one session is used? There are multiple ways. One of the easiest I can think of, is using a database session handler for storing your sessions and when a user logs in, check whether there is an existing active session for that user by querying your table. Most frameworks like Zend Framework or Symfony provide a database session handler you can use as example.

Upvotes: 2

Bruno Gomes
Bruno Gomes

Reputation: 113

thinking that the session is valid for domain and by machine, then you have a unique User per session.

Upvotes: 0

Related Questions