0

I have a session like this $_SESSION['login'] and when it is equal with 1, it means the use is logged into my website:

if ( $_SESSION['login'] == 1 ) {
    // You are logged
} else {
    // login/register
}

Also I have another session which contains user's id. Something like this:

echo $_SESSION["Id"]; 
/* It is containing the user's id (an integer number).
   Something like: 234124
*/

Now I want to unset $_SESSION['login'] for the user who has a specific id. For example I want to unset($_SESSION['login']) for $_SESSION["Id"] = 234124. How can I do that?


Edit: All I'm trying to do: When an user changes his password, I remove all his cookies from cookies table to sign him out from all his other devices. Also I want to remove his session.

stack
  • 10,280
  • 19
  • 65
  • 117

1 Answers1

3

If I understood your right, you want to sign out a user completely, i.e. from all sessions (from a laptop, a mobile phone, etc.).

It's only possible when 1) you have a mapping user_id => session_id and 2) you can query sessions somehow. For example, when you store sessions in a database table, and you have user_id as a column in this table, you can simply delete all sessions for a user (or just modify them).

But it's not possible with default PHP session handler. You don't have such type of mapping available.

I advise you to write a custom session handler that stores sessions in a database table. To build the mapping, you can override write method and extract your user_id there. Be careful with serialized data, pay attention to session.serialize_handler configuration directive.

For example,

php.ini

session.serialize_handler = php_serialize

session handler

public function write($id, $data)
{
    $content = unserialize($data);

    return $this->db->insert('sessions', [
        'id' => $id,
        'user_id' => $content['user_id'],
        'data' => $data,
    ]);
}

and control code

if (...) {
    $db->execute('DELETE FROM sessions WHERE user_id = ?', $userId);
}
Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22