简体   繁体   中英

how to force logout using $_SESSION

When a user successfully authenticates on my site, i store their user id in session: $_SESSION['user_id']

I then use this throughout the site to check if the user can perform certain actions. eg

if(isset($_SESSION['user_id'])){
    //User is logged in, allow the following.
    ...
}

...

if ( $_SESSION['user_id'] == $comment_user ) {
    //User owns the comment, go ahead and delete it.
    ...
}

However, if i discover that a signed in user has malicious purposes, how can i kill their login session so that they cannot perform these secure actions?

To block the user, on the db I can invalidate their login details, or add them to a blocked list that is checked upon authentication so that they can no longer authenticate. However, this would only have effect when they next attempt to log in. As long as the current session remains active and their user id is stored in session, they are considered authenticated..

  1. Is there a way to unset a specific session, forcing a logout? How?
  2. If not, what is the best way to make sure blocked users cannot continue to access secure areas on the site? eg My only idea is rather than just checking if(isset($_SESSION['user_id'])) , an additional check can be added to make sure the user_id hasn't been added to a "blocked users" list on the db. I just don't like that another db request is made to check if the user has been to a blocked list each time they perform some action. Especially because blocking a user would be a rare occurrence. Is there a way to check if the user has been blocked without going to the db?

Thanks!

Edit

Most answers so far address how to unset/destroy a session, or how to block a user from their next login attempt. I guess the only question remaining then is how to check whether a user has been blocked while they are currently logged in. Is there is a way to do this without going to the DB to check a "blocked users" list each time a user performs an action. This relates to my main issue, which in bold italics above. If the user is blocked then i can immediately destroy the session (forcing a logout) and they will also be prevented from authenticating again.

when using sessions for authentication it is traditionally done with a username and some sort of hashed password stored as session variables. Here's a good resource on that: php sessions to authenticate user on login form

to end a user's session:

with your setup you can simply remove the session variable for the user to end their session

unset($_SESSION['user_id']);

or you can simply end the session like this:

session_destroy();

If you know the user ID, you can always do something like:

$maliciousUsers = array(1,3,19,24);

if(in_array($_SESSION['user_id'], $maliciousUsers)){
    @session_destroy();
}

I would do the $maliciousUsers array as a table in the database. This way, if you see something happening, toss their ID into the table, and it will be reflected. If they are able to authenticate and receive a $_SESSION['user_id'] then, this will destroy it.

I have a tendency to put in a self destruct in the sessions table. on their next login, the app checks this.

if (!!$_SESSION['data']['self_destruct'])
{
    session_destroy();
    header('Location:/');
    exit;
}

Presuming you're using a DB, storing the session identifier in there and banning them from any future logins, then the easiest way of achieving this is to additionally delete their session file from your file-system.


Finding session files

PHP sessions are often stored in the /temp or /tmp or /var/lib/php5/ directory (It varies) - although the default session.save_path is set to "" , you can set the location by using:

session_save_path('/path/to/session/dir');

Or even in your .htaccess file:

php_value session.save_path /path/to/session/dir/


How session files are stored

Session files are prefixed with sess_ within a file system:

-rw-------  1 www-data www-data    0 2013-04-19 05:39 sess_141d2215ce74452ea6b1f69eea228159

Which, in the above example contains:

AutoLogout|s:4:"3600";FirstName|s:4:"John";Lang|s:2:"en";LastLogin|s:19:"2013-04-19 17:26:18";LastName|s:8:"Smith";RegDate|s:19:"2012-11-12 17:18:13";TimeOut|i:1366421178;UserEmail|s:22:"johnsmith@domain.com";UserId|s:1:"3";authenticatedUser|s:22:"johnsmith@domain.com";year|s:4:"2013";

As long as you have a record of their ID (assuming in your DB), you can delete them programatically.


Deleting session files instantly using PHP

PHP provides the ability to delete a file using unlink() and thus, when banning a user and preventing them from logging in (in the future), you can also ban them instantly by appending something like this to your banning function or creating an instant-kick function, using something like:

$sessionID = 'sess_'.$sessionIdFromDB;
$sessionDir = '/path/to/session/dir'; // Wherever your sessions are stored
unlink($sessionDir."/".$sessionID); 

However, this technique assumes you have the permissions to delete the session file in question. If you don't, then you would need to adjust the file permissions or change them using chown() and/or chmod() or on your file-system.


Manual deletion

You can also delete session files manually using a terminal. Whilst this might seem pointless, I've seen it used in the past to instantaneously kick all users out prior to doing something business specific:

//SSH
cd /path/to/session/dir
rm -rf sess_*

Which, once executed, invalidates all user sessions.

Is there a way to unset a specific session, forcing a logout? How?

Better To Perform a Quick Logout

 May be late but commented 

//Change Accordingly!

function doLogout()
{
        //clear session from globals
        $_SESSION = array();
        //clear session from disk
        session_destroy();
        //delete the session cookie using setcookie.
        $cookieParams = session_get_cookie_params();
        setcookie(session_name(), '', 0, $cookieParams['path'], $cookieParams['domain'], $cookieParams['secure'], $cookieParams['httponly']);
        //unset the session variable
        unset($_SESSION);
        doBlock();   

}

    function doBlock()
        {               

     //Start and Set Blocking session ,presence of it must be 
    //validated at first on any secure Areas Entrance   , 
   //it may not be secure if Session is Cleared by end Mal User) ,
  // if extreme   security is needed  then
 //Ugly block Remote IP is needed //(12-24 hr) Block

 }

your Quest may have duplicates : Best way to completely destroy a session - even if the browser is not closed
How to remove a variable from a PHP session array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM